a == null 和 a === null 有什么区别?(涉及IT技术)

20

有人可以帮忙解释一下吗?我理解的是 === 会进行精确匹配,但是与 null 进行比较时具体意味着什么呢?


请查看https://dev59.com/Z3RC5IYBdhLWcg3wROpQ#359509。 - Phillip Kinkade
2
undefined === nullfalseundefined == nulltrue -> 在大多数情况下,您会使用 == 来同时处理 nullundefined - Vedran
5个回答

25
与null进行比较时,这是什么意思?
这意味着它检查该值是否完全等于null。
如果a的值为null,那么a === null 将会是true。
参见规范中的严格相等比较算法

1. 如果Type(x)Type(y)不同,则返回false。
2. 如果Type(x)是Undefined,则返回true。
3. 如果Type(x)是Null,则返回true。

因此,只有当Type(a)为Null时,比较才会返回true。
重要提示:不要将内部的Type函数与typeof运算符混淆。typeof null实际上会返回字符串"object",这更令人困惑而不是帮助。
a == null 如果变量 a 的值为 nullundefined,则返回 true。
请参阅规范中的 抽象相等比较算法

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


很酷的东西,不错的链接! - JoeC

0

=== 是一个严格的运算符,它不仅比较值,还比较变量的类型。

string===string
int===int

== 只比较值。


0

=== 表示它会检查变量的值和类型。例如从 w3c 页面中提取,给定 x = 5,x 是一个 int,所以 x==="5" 是 false,因为它比较的是 int 和 string,而 x ===5 是 true,因为它既是 int 类型又是正确的值。


3
好的,但是OP特别问及与“null”情况的比较,请提供一个好的例子。 - adamdunson

0

使用三个等号,值必须在类型上相等。但不适用于 ==。

i.e

1==true // this return true
1===true // but return false

a==null // will true if a is null or undefined

-1

1==true 将会是 true

但是 1===true 将会是 false

例如,=== 是在数据类型级别上进行比较,而使用 == 时,JavaScript 会自动进行类型转换


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