开发者

How come this is true? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why does (0 < 5 <3) return true?

How come this is tru开发者_开发技巧e?:

console.log(100 < 210 < 200); // outputs true


That's equivalent to:

console.log((100 < 210) < 200);

which is equivalent to:

console.log(true < 200);

And this evaluates to true because when using operators like <, true is treated as if it were a 1

Consequently, the following will evaluate to false:

console.log(true < 0)


100 < 210 < 200 is equivalent to (100 < 210) < 200 which is true < 200 which is 1 < 200 which is true.

That last bit (true becoming 1) may be a bit surprising. It's the result of how JavaScript does relational operations (Section 11.8.5 of the spec), which says amongst other things that if the relation is between a non-number (other than null or undefined) and a number, you convert the non-number to a number, and the conversion of true to a number results in 1 (Section 9.3 of the spec.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜