为什么alert(!!" 0")和alert(false ==" 0")都在JavaScript中输出为true [英] Why do alert(!!"0") and alert(false == "0") both output true in JavaScript
问题描述
据我所知,在JavaScript!应该规范化一个布尔值,将其从某个其他类型转换为true或false。这意味着0转换为布尔值true。另一方面,如果我将它与false进行比较,事实证明它实际上是假的(因为比较的结果是真的)。我在这里错过了什么规则。我已经在IE和Opera中测试了它。
As far as I know in JavaScript !! is supposed to normalize a boolean value converting it to true or false from some other type. This would mean that the "0" converts to boolean true. On the other hand if I compare it with false it turns out that it is in fact false (as the result of the comparison is true). What rule am I missing here. I have tested it in IE and Opera.
推荐答案
==
运算符检查松散的相等性,这与真实性无关。
The ==
operator checks for loose equality, which has nothing to do with truthiness.
具体来说,它会将操作数转换为数字,然后比较数字。
包含数字的字符串将转换为它们包含的数字;布尔值转换为 0
和 1
。
通过调用 valueOf
,如果已定义。
Specifically, it will convert to operands to numbers, then compare the numbers.
Strings containing numbers convert to the numbers that they contain; booleans convert to 0
and 1
.
Objects are converted by calling valueOf
, if defined.
因此,以下所有条件均为真:
Thus, all of the following are true:
-
1== 1
-
0== false
-
1== true
-
2!= true
-
2!= false
-
({valueOf:function(){return 2;}})== 2
-
({valueOf:function(){return 1;}})== true
"1" == 1
"0" == false
"1" == true
"2" != true
"2" != false
({ valueOf:function() { return 2; } }) == 2
({ valueOf:function() { return 1; } }) == true
这篇关于为什么alert(!!" 0")和alert(false ==" 0")都在JavaScript中输出为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!