更新时间:2022-10-27 12:49:19
这是因为抽象等式比较算法要求如果 Type(x)
或 类型(y)
是一个布尔值表达式 x == y
然后应通过将布尔值强制转换为数字 ToNumber
,将 true
转换为1, false
到 +0
。
这意味着的所有比较都是真的==某事
或某事== true
结果 1 ==某事
或某事== 1
(替换 true
和 1
, false
和 +0
对于 false
)。
Null类型不等于1或+ 0(事实上,null只能与AECA中的 undefined
相比)。 / p>
在 MDN 如果你想了解更多信息,那么值得一看。
然而,如果你强迫 null
到一个数字是强迫 +0
所以 + null == false
实际上返回 true
。
I know that null
is an object with no attributes or functions.
However, I am confused that why console.log(null == false);
and console.log(null == true);
both return false.
What are the conversion rules between null
and boolean
?
This is because the Abstract Equality Comparison Algorithm requires that if Type(x)
or Type(y)
is a Boolean in the expression x == y
then the Boolean value should be coerced to a number via ToNumber
, which converts true
to 1 and false
to +0
.
This means that any comparison of true == something
or something == true
results in 1 == something
or something == 1
(replacing true
and 1
with false
and +0
for false
).
The Null type does not compare as equal to either 1 or +0 (in fact, null is only comparable to undefined
in the AECA).
There is a detailed discussion of all of the different kinds of equality in JavaScript on MDN that is well worth looking at if you want to know more.
However, if you coerce null
to a number it is coerced to +0
so +null == false
actually returns true
.