Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

How does (A == B == C) comparison work in JavaScript?

I was expecting the following comparison to give an error:

var A = B = 0;
if(A == B == 0)
    console.log(true);
else
    console.log(false);

but strangely it returns false.

Even more strangely,

console.log((A == B == 1)); 

returns true.

How does this "ternary" kind of comparison work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assignment operators like = are right-associative: when there is a series of these operators that have the same precedence, they are processed right-to-left, so A = B = 0 is processed as A = (B = 0) (B = 0 returns 0, so both A and B end up as 0).

Equality operators like == are left-associative: same-precedence operators are processed left-to-right. A == B == 0 is processed as (A == B) == 0, and since A == B is true (1), it becomes 1 == 0, which is false (0).

Likewise, A == B == 1 is processed as (A == B) == 1, which becomes 1 == 1, which is true (1).

Source and more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...