-1 == true; // false
-1 == false // false
-1 ? true : false; // true
有人能解释上面的输出吗?我知道我可以通过与0进行比较来解决这个问题,但我很感兴趣。由于它们执行隐式类型转换,我期望至少有一个松散相等语句为真,而我肯定没有预料到三元运算符会得出完全不同的结果。
-1 == true; // false
-1 == false // false
-1 ? true : false; // true
有人能解释上面的输出吗?我知道我可以通过与0进行比较来解决这个问题,但我很感兴趣。由于它们执行隐式类型转换,我期望至少有一个松散相等语句为真,而我肯定没有预料到三元运算符会得出完全不同的结果。
-1 == 1; // false
-1 == 0; // false
true ? true : false; // true
值得一读的是完整的算法,因为其他类型可能会引起更糟糕的错误。19. 如果y的类型是布尔型,则返回比较x == ToNumber(y)的结果。
Boolean(-1)
进行 true 强制转换,你会发现 -1 仍然被视为 true (即非 0)。 - Rudu2 == true
输出false?“2”是一个数字。 - jack blanktrue
是相同的真值。因此,-1 == true
不一定成立,但-1
仍然可以被认为是一个真值,因为它是非零的。When evaluated as a test condition, integers like -1, 5 and 17,000,000, all return Boolean true, because they logically evaluate to true, e.g.
if(-1) {
"This is true";
}
else {
"This is false";
}
=> "This is true";
(Note: 0 logically evaluates to false)
Using the "?" operator does what this code just does. It passes the first argument as a condition in an if statement, passes the second argument as the true case, and passes the third argument as the false case.
Hence the third result.
However, these integers are not of the same type as true.
True is of type Boolean, -1, 5 and 17,000,000 are of type Integer.
The comparison '==' is strict, in terms of type comparison. Even two things have the same "value", but not the same type, the "==" operator returns false:
if(6 == true) {
"This is true";
}
else {
"This is false";
}
=> "This is false";
Even the following will return false, because "true" is of type String and true is of type Boolean:
if("true" == true) {
"This is true";
}
else {
"This is false";
}
=> "This is false";
Hence, the first two results.
Note: If you'd like to compare values irregardless of type, use the "===" operator:
if(6 === true) {
"This is true";
}
else {
"This is false";
}
=> "This is true";
and also,
if("true" === true) {
"This is true";
}
else {
"This is false";
}
=> "This is true";
Hope this helps!