未定义和空值

9
undefined === null => false
undefined == null => true
  1. I have thought about the reason of undefined == null and found out only one case:

    if(document.getElementById() == null) ....
    

    Is there any other reason to make (undefined === null) == false ?

  2. Is there any other examples of use === - operation in javascript?

4个回答

11

是否有其他原因使得(undefined === null)== false?

它们不相等,因此严格相等比较算法将它们视为false。

在JavaScript中是否还有其他使用===运算符的例子?

===给出最可预测的结果。只有当我需要进行类型强制转换时才会使用==。(参见抽象相等比较算法。)


1
@Raynos:是的,我等了几秒钟,这样你就可以追上我了。 ;o) - user113716

4

nullundefined是两个不同的概念。 undefined表示缺少值(如果您使用var定义变量而不初始化它,则它不包含null,但包含undefined),而使用null时,变量存在并且已初始化为值null,这是一种特殊类型的值。

然而,JavaScript中的相等运算符存在问题。Crockford发现它缺乏传递性,因此建议始终使用严格相等(===)。请考虑在《JavaScript语言精髓》中发布的此表格:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true

false == 'false'   // false
false == '0'       // true

false == undefined // false
false == null      // false
null == undefined  // true

2
“未定义”是缺少值的意思(可能变量不存在),这并不完全正确。使用“未定义”,变量确实存在,但它已被分配(或重新分配)为其默认值“未定义”。如果您尝试与不存在的变量进行比较,则会出现“引用错误(ReferenceError)”。 - user113716

3

=== 是严格相等。

未定义和null并不是同一件事情。

== 使用类型强制转换。

nullundefined 会相互转换。


3

类型转换(使用 == 运算符)可能会导致不期望的结果。在查看了我能找到的所有 Douglas Crockford 关于 JavaScript 的演讲(主要是雅虎视频),我习惯于一直使用 === 。考虑到我的默认使用严格相等运算符,我现在更加关注类型转换在 JavaScript 中的用例 ;~)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接