Bootstrap

undefined == null的正确解释

console.log( undefined == null )  //true

有文章对此进行了解释,大致是下面的意思:undefined的布尔值是false,null的布尔值也是false,所以它们在比较时都转化为了false,所以 undefined == null 。

好吧,上面的解释是错误的。


可以从Javascript规范中找到答案:

规范中提到, 要比较相等性之前,不能将 null 和 undefined 转换成其他任何值,并且规定null 和 undefined 是相等的。

null 和 undefined都代表着无效的值。


全等于状态下,是false,这个很好理解了。它们不属于同一数据类型。

console.log( undefined === null )  //false
 typeof null        //object
 typeof undefined       //undefined