empty与isset,null与undefined

一. null VS undefined VS NaN

1. null

定义:null是特殊的object,是空对象,没有任何属性和方法。

document.writeln(typeof null); // object  

值得注意的是: 对象模型中,所有的对象都是Object或其子类的实例,但null对象例外:

document.writeln(null instanceof Object); // false  

2. undefined

定义:undefined是undefined类型的值,未定义的值和定义未赋值的为undefined;无法使用 for/in 循环来枚举 undefined 属性,也不能用 delete 运算符来删除它。

作用

(1)变量被声明了,但没有赋值时,就等于undefined。

(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。

(3)对象没有赋值的属性,该属性的值为undefined。

(4)函数没有返回值时,默认返回undefined。

var i;
i // undefined

function f(x){console.log(x)}
f() // undefined

var  o = new Object();
o.p // undefined

var x = f();
x // undefined

提示:只能用 === 运算来测试某个值是否是未定义的,因为 == 运算符认为 undefined 值等价于 null
注释:null 表示无值,而 undefined 表示一个未声明的变量,或已声明但没有赋值的变量,或一个并不存在的对象属性。

3. NaN

NaN是一种特殊的number

document.writeln(typeof NaN); // number  

他们三个的值

 1. null“等值(==)”于undefined,但不“全等值(===)”于undefined,NaN与任何值都不相等,与自己也不相等:

document.writeln(null == undefined); // true    
document.writeln(null === undefined); // false  
document.writeln(NaN == null); // false  
document.writeln(NaN == undefined); // false  
document.writeln(NaN == NaN); // false  

2.  null与undefined都可以转换成false,但不等值于false: 

document.writeln(!null, !undefined); // true true    
document.writeln(undefined == false); // false    
document.writeln(null == false); // false  

3. null不等于0,但是计算中null会当做成0来处理undefined计算的结果是NaNNaN计算的结果也是NaN

alert(null == 0); // false  
alert(123 + null); // 123  
alert(123 * null); // 0  
alert(123 / null); // Infinity  
alert(123 + undefined); // NaN  
alert(123 * undefined); // NaN  
alert(123 / undefined); // NaN  
alert(123 + NaN); // NaN  
alert(123 * NaN); // NaN  
alert(123 / NaN); // NaN  

二. empty VS isset

1. empty

检查一个变量是否为空(变量不存在或它的值等同于FALSE),如果变量不存在empty()不会产生警告。

2. isset

检测变量是否设置,并且不是 NULL

<?php

$var = '';

// 结果为 TRUE,所以后边的文本将被打印出来。
if (isset($var)) {
    echo "This var is set so I will print.";
}

// 在后边的例子中,我们将使用 var_dump 输出 isset() 的返回值。
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>
原文地址:https://www.cnblogs.com/lesleysbw/p/6957886.html