为什么(null == false)和(null == true)都返回false? [英] Why (null == false) and (null == true) both return false?
问题描述
我知道 null
是一个没有属性或功能的对象。
然而,我很困惑为什么 console.log(null == false);
和 console.log(null == true);
两者都返回false。
null
和 boolean $ c $之间的转换规则是什么c>?
这是因为抽象等式比较算法要求如果 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
.
这篇关于为什么(null == false)和(null == true)都返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!