在 JavaScript 中使用 == 进行比较时,!0 转换为什么?
What is !0 converted to when compared using == in JavaScript?
我在控制台中尝试了一些操作。
!5 is actually false
0 is a falsy value, so
0 == !5 is true
好的,但是当我尝试这个时
!0 is true
5 is a truthy, so
5 == !0 should be true
但它不是,控制台显示错误。 为什么会这样?
最后一行是 false
的原因是 ==
不是简单的布尔转换。它通常 尝试将具有不匹配类型的操作数转换为数字。
所以 5
不需要转换,因为它已经是一个数字,但是 !0
,即 true
,需要转换。值 true
被转换为 1
,因此它不等于 5
。
由此可以推断1 == !0
将是true
,确实如此。
这在 Abstract Equality Comparison Algorithm 的 ES5 规范中有详细说明,第 7 步提到了比较 x == y
:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
所以右边的布尔值被强制转换为 ToNumber 的数字。在这种情况下,ToNumber 表示:
The result is 1 if the argument is true.
我在控制台中尝试了一些操作。
!5 is actually false
0 is a falsy value, so
0 == !5 is true
好的,但是当我尝试这个时
!0 is true
5 is a truthy, so
5 == !0 should be true
但它不是,控制台显示错误。 为什么会这样?
最后一行是 false
的原因是 ==
不是简单的布尔转换。它通常 尝试将具有不匹配类型的操作数转换为数字。
所以 5
不需要转换,因为它已经是一个数字,但是 !0
,即 true
,需要转换。值 true
被转换为 1
,因此它不等于 5
。
由此可以推断1 == !0
将是true
,确实如此。
这在 Abstract Equality Comparison Algorithm 的 ES5 规范中有详细说明,第 7 步提到了比较 x == y
:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
所以右边的布尔值被强制转换为 ToNumber 的数字。在这种情况下,ToNumber 表示:
The result is 1 if the argument is true.