- 为什么undefined==null
其实在 ECMAScript 的原始类型中,是有Undefined 和 Null 类型的。 这两种类型都分别对应了属于自己的唯一专用值,即undefined 和 null。
Undefined 类型只有一个值,就是特殊值 undefined。当使用 var 或 let声明了变量但没有初始化时,就相当于给变量赋予了 undefined 值 。
注意:
增加这个特殊值的目的就是为了正式明确空对象指针(null)和未初始化变量的区别。
Null 类型同样只有一个值,即特殊值 null。逻辑上讲,null 值表示一个空对象指针。
undefined 值是由 null 值派生而来的,因此 ECMA-262 将它们定义为表面上相等。
console.log(undefined == null); //true
也可以从Javascript规范中找到答案:
规范中提到, 要比较相等性之前,不能将 null 和 undefined 转换成其他任何值,并且规定null 和 undefined 是相等的。
- 为什么 undefined !== null
null 和 undefined都代表着无效的值。
尽管这两个值相等,但它们的含义不同。
undefined
声明了变量但未对其初始化时赋予该变量的值。
null
则用于表示尚未存在的对象。
如果函数或方法要返回的是对象,那么找不到该对象时,返回的通常是 null。
全等于状态下,是false,这个很好理解了。它们不属于同一数据类型。
console.log( undefined === null ) //false
typeof null //object
typeof undefined //undefined
Udefined代表没有赋值的基本数据类型,Null代表没有赋值的引用数据类型。
typeof null 返回object,因为null代表是无值的引用。
undefined是全局对象(window)的一个特殊属性,其值为Undefined类型的专用值undefined。
同样的
console.log( null instance of object ) //false
- null和undefined参与运算
null 参与数值运算时其值会自动转换为 0。
因此,下列表达式计算后会得到正确的数值:
console.log( null + 1 ) //1
undefined参与任何数值计算时,其结果一定是NaN。
console.log( undefined + 1 ) //NaN