问题
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