问题描述
据我所知,(x == false)
应该和 !x
做同样的事情,因为它们都试图解释 x
作为布尔值,然后取反.
To the best of my knowledge, (x == false)
should do the same thing as !x
, as both of them try to interpret x
as a boolean, and then negates it.
然而,当我尝试对此进行测试时,我开始出现一些非常奇怪的行为.
However, when I tried to test this out, I started getting some extremely strange behavior.
例如:
false == []
和 false == ![]
都返回 true.
false == []
and false == ![]
both return true.
另外
false == undefined
和 true == undefined
都返回 false,同样
false == undefined
and true == undefined
both return false, as does
false == Infinity
和 true == Infinity
和
false == NaN
和 true == NaN
.
这里到底发生了什么?
推荐答案
都在这里:http://es5.github.com/#x11.9.3
对于false == []
的情况:
false
被转换为数字 (0),因为这总是用布尔值完成的.- [] 通过调用
[].valueOf().toString()
被转换为原语,即空字符串. 0 == ""
然后通过将空字符串转换为数字来评估,并且因为其结果也是 0,所以false == []
是是的.
false
is converted to a number (0), because that is always done with booleans.- [] is converted to a primitive by calling
[].valueOf().toString()
, and that is an empty string. 0 == ""
is then evaluated by converting the empty string to a number, and because the result of that is also 0,false == []
is true.
对于false == ![]
的情况:
- 逻辑非运算符
!
通过返回与ToBoolean(GetValue(expr))
相反 ToBoolean()
对于任何对象始终为真,所以![]
计算结果为false
(因为!true = false
),因此是false == ![]也是如此.
The logical not operator
!
is performed by returning the opposite ofToBoolean(GetValue(expr))
ToBoolean()
is always true for any object, so![]
evaluates tofalse
(because!true = false
), and therefore isfalse == ![]
also true.
(false == undefined) === false
和 (true == undefined) === false
更简单:
false
和true
再次转换为数字(分别为 0 和 1).因为 undefined 不能与数字进行比较,所以链会冒泡到默认结果,即
false
.
false
andtrue
are again converted to numbers (0 and 1, respectively).Because undefined cannot be compared to a number, the chain bubbles through to the default result and that is
false
.
其他两种情况的计算方式相同:首先将布尔值转换为数字,然后将其与其他数字进行比较.由于 0 和 1 都不等于无穷大或不是数字,因此这些表达式的计算结果也为
false
.
The other two cases are evaluated the same way: First Boolean to Number, and then compare this to the other number. Since neither 0 nor 1 equals Infinity or is Not A Number, those expressions also evaluate to
false
.
这篇关于在对象到布尔值的情况下,Javascript 中的类型强制如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!