【问题标题】:What's the difference between a == null and a === null? [duplicate]a == null 和 a === null 有什么区别? [复制]
【发布时间】:2013-12-19 17:26:51
【问题描述】:

谁能帮我解释一下区别。据我了解, === 完全匹配,但与 null 比较时这意味着什么?

【问题讨论】:

  • undefined === nullfalseundefined == nulltrue -> 在大多数情况下,您会使用 == 同时处理 nullundefined

标签: javascript


【解决方案1】:

与null比较是什么意思?

这正是你所说的:它检查值是否正是null


如果a 的值为null,则a === null 为真。

The Strict Equality Comparison Algorithm in the specification:

1。如果Type(x)Type(y) 不同,则返回false。
2.如果Type(x)未定义,则返回true。
3.如果Type(x)为Null,则返回true。

所以,只有Type(a) 为 Null,比较才会返回 true。

重要提示:不要将内部Type 函数与typeof 运算符混淆。 typeof null 实际上会返回字符串"object",这比帮助更令人困惑。


如果a 的值为nullundefined,则a == null 为真。

The Abstract Equality Comparison Algorithm in the specification:

2。如果xnull 并且yundefined,则返回true。
3.如果xundefinedynull,返回true。

【讨论】:

  • 很酷的东西,不错的链接!
【解决方案2】:

=== 表示它同时检查变量的值和类型。例如从 w3c 页面中提取,给定 x = 5,x 是一个 int,所以 x==="5" 是 false,因为它正在将 int 与 string 进行比较,而 x ===5 是 true,因为它都是 int和正确的价值。

【讨论】:

  • 很好的例子,但 OP 专门询问与null 案例的比较。
【解决方案3】:

=== 是严格运算符,它不仅比较值,而且比较变量的类型,所以

string===string
int===int

== 只比较值。

【讨论】:

    【解决方案4】:

    使用三等号,值也必须在类型上相等。但在 == 中则不然。

    1==true // this return true
    1===true // but return false
    
    a==null // will true if a is null or undefined
    

    【讨论】:

      【解决方案5】:

      1==true 将是 true

      1===true 将是false

      例如。 === 在使用 == 时在数据类型级别上进行比较@ JavaScript 将自行进行类型转换

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-23
        • 2013-06-25
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        相关资源
        最近更新 更多