变量a分别被赋值为undefined和null,这两种写法的效果几乎等价。
在if语句中,它们都会被自动转为false,相等运算符(==)甚至直接报告两者相等。
注意
if (!undefined) {console.log('undefined is false');}// undefined is falseif (!null) {console.log('null is false');}// null is falseundefined == null// true
// null is falseundefined == null// true
历史原因
1995年 JavaScript 诞生时,最初像 Java 一样,只设置了null表示”无”。根据 C 语言的传统,null可以自动转为0。
Number(null) // 05 + null // 5
上面代码中,null转为数字时,自动变成0。
但是,JavaScript 的设计者 Brendan Eich,觉得这样做还不够。首先,第一版的 JavaScript 里面,null就像在 Java 里一样,被当成一个对象(typeof null为Object),Brendan Eich 觉得表示“无”的值最好不是对象。其次,那时的 JavaScript 不包括错误处理机制,Brendan Eich 觉得,如果null自动转为0,很不容易发现错误。
因此,他又设计了一个undefined。区别是这样的:<font style="color:#F5222D;">null</font>是一个表示“空”的对象,转为数值时为<font style="color:#F5222D;">0</font>;<font style="color:#F5222D;">undefined</font>是一个表示”此处无定义”的原始值,转为数值时为<font style="color:#F5222D;">NaN</font>。
Number(undefined) // NaN5 + undefined // NaN
null
<font style="color:#F5222D;">null</font>表示空值,即该处的值现在为空,转为数值时为<font style="color:#F5222D;">0</font>。调用函数时,某个参数未设置任何值,这时就可以传入null,表示该参数为空。比如,某个函数接受引擎抛出的错误作为参数,如果运行过程中未出错,那么这个参数就会传入null,表示未发生错误。
undefined
<font style="color:#F5222D;">undefined</font>表示“未定义”,转为数值时为<font style="color:#F5222D;">NaN</font>,下面是返回undefined的典型场景。
// 变量声明了,但没有赋值var i;i // undefined// 调用函数时,应该提供的参数没有提供,该参数等于 undefinedfunction f(x) {return x;}f() // undefined// 对象没有赋值的属性var o = new Object();o.p // undefined// 函数没有返回值时,默认返回 undefinedfunction f() {}f() // undefined
