Can I use chained comparison operator syntax?

后端 未结 6 2123
醉话见心
醉话见心 2020-12-19 17:30

In one JS library I saw such syntax:

if (val > 5 == t) { ... }

I tested this in console:

1 == 1 == 2 // false
2 > 1 =         


        
6条回答
  •  半阙折子戏
    2020-12-19 17:45

    1 == 1 == 2  // this
    true == 2    // becomes this
    1 == 2       // which becomes this, and is false
    
    2 > 1 == 1  // this
    true == 1   // becomes this
    1 == 1      // which becomes this, and is true
    

    ...and so on.

    If you're wondering about the conversion, you should do a search on the == operator, which uses the Abstract Equality Comparison Algorithm.

提交回复
热议问题