Why do alert(!!"0") and alert(false == "0") both output true in JavaScript
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 wo开发者_StackOverflowuld 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.
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
In the first case, a non-empty string is equivalent to true.
In the second case, because one operand is a boolean, both operands are converted to numeric values. I believe false
converts to the numeric value 0
and the string "0"
also converts to a numeric 0
, resulting in 0 == 0
which is true.
Check out the Mozilla reference for operator behavior.
For the first expression, section 9.2 of ECMA-262 defines an abstract operation ToBoolean internally used by the logical NOT operator. It says:
String
The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
For the second expression, JavaScript will perform type coercion when it attempts to compare these values of different data types. Douglas Crockford says that this is a misfeature. It would be false if you had used ===
instead of ==
. The rules are rather complex, so you should directly look in section 11.9.3 of ECMA-262 for the details.
精彩评论