JavaScript triple equals and three-variable comparison

佐手、 提交于 2019-11-28 08:24:45

问题


Can somebody explain this?

1 == 1        //true, as expected
1 === 1       //true, as expected
1 == 1 == 1   //true, as expected
1 == 1 == 2   //false, as expected
1 === 1 === 2 //false, as expected
1 === 1 === 1 //false? <--

Also is there a name for boolean logic that compares more than two numbers in this way (I called it "three-variable comparison" but I think that'd be wrong...)


回答1:


This expression:

1 === 1 === 1

Is evaluated as:

(1 === 1) === 1

After evaluating the expression inside parentheses:

true === 1

And that expression is logically false. The below expression returns true as expected though:

1 === 1 === true



回答2:


Equality is a left-to-right precedence operation.

So:

1 == 1 == 1
true == 1
true

And:

1 === 1 === 1
true === 1
false // because triple-equals checks type as well


来源:https://stackoverflow.com/questions/15331947/javascript-triple-equals-and-three-variable-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!