简体   繁体   中英

How does the identity operator in JavaScript work?

为什么(9 > 8) === true导致“ true ”,而(10>9>8) === true导致“ false ”?

If we see both, the JavaScript executes from left to right. As we all know:

(9 > 8) === true

The above statement is indeed true. But what we need to know is, how JavaScript executes this. If we see how it gets executed, the execution steps are as below:

(10 > 9 > 8) === true
((10 > 9) > 8) === true
(true > 8) === true
(1 > 8) === true
false === true
false

Because:

10 > 9 > 8 === (true) > 8

Which is false. In truthy values, a true gets expressed as "1". Since true > 0 and false < 1 .

You should only have one comparative operator without using the AND(&&) or the OR(||) operators.

If you want (10>9>8) to resolve to true, you would format it like this:

(10 > 9 && 9 > 8)

this says "check 10 > 9, if that's true, check 9 > 8. If they're both true, return true"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM