Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

boolean logic - Why are JavaScript negative numbers not always true or false?

-1 == true;        // false
-1 == false        // false
-1 ? true : false; // true

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

The same would be true of any number that isn't 0 or 1.

For more detail, read the ECMAScript documentation. From the 3rd edition [PDF], section 11.9.3 The Abstract Equality Comparison Algorithm:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...