为什么Javascript负数不总是真或假? [英] why are Javascript negative numbers not always true or false?
问题描述
-1 == true; //false
-1 == false //false
-1 ? true : false; //true
任何人都可以解释上述输出吗?我知道我可以通过比较0来解决这个问题,但我很感兴趣。我希望至少有一个草率的equals语句是真实的,因为它们进行隐式类型转换,我当然没想到三元组会得出完全不同的结果。
Can anyone explain the above output? I know I could work round this by comparing to 0 but I'm interested. I'd expect at least one of the sloppy equals statements to be true as they do implicit type conversion, and I certainly didn't expect the ternary to come up with a totally different result.
推荐答案
在前两种情况下,布尔值被强制转换为数字 - 1表示 true ,0表示 false 。在最后一种情况下,它是一个强制转换为布尔值的数字,除0和NaN之外的任何数字都将转换为 true 。所以你的测试用例更像是这样:
In the first two cases, the boolean is cast to a number - 1 for true and 0 for false. In the final case, it is a number that is cast to a boolean and any number except for 0 and NaN will cast to true. So your test cases are really more like this:
-1 == 1; // false
-1 == 0; // false
true ? true : false; // true
任何非0或1的数字都是如此。
The same would be true of any number that isn't 0 or 1.
有关更多详细信息,请阅读ECMAScript文档。来自第3版[PDF] ,部分 11.9.3抽象等式比较算法:
For more detail, read the ECMAScript documentation. From the 3rd edition [PDF], section 11.9.3 The Abstract Equality Comparison Algorithm:
19 。如果Type(y)是布尔值,则返回比较结果x == ToNumber(y)。
19. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
值得给出全部算法读取,因为其他类型可能导致更糟糕的陷阱。
It's worth giving the full algorithm a read because other types can cause worse gotchas.
这篇关于为什么Javascript负数不总是真或假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!