问题
I've got 3 random numbers (in this specific case between 1 and 7 but it doesn't really matter). I want to check whether I got "three of a kind" by using
if (x==y==z) {
code
}
The problem is that when x==y
and z==1
x==y==z
will return true. How do I check whether x, y and z actually got the SAME value?
Example: 5==5==1
will return true, how do I check for 5==5==5
specifically? (Excluding 5==5==1
)
回答1:
By doing a proper comparison:
x === y && y === z
// due to transitivity, if the above expression is true, x === z must be true as well
x==y==z
is actually evaluated as
(x == y) == z
i.e. you are either comparing true == z
or false == z
which I think is not what you want. In addition, it does type conversion. To give you an extreme example:
[1,2,4] == 42 == "\n" // true
The problem is that when
x==y
andz==1
,x==y==z
will return true.
Yes, because x == y
will be true
, so you compare true == 1
. true
will be converted to the number 1
and 1 == 1
is true
.
回答2:
You should check with separate &&
operations
if(x == y && x == z){
//all are equal
}
来源:https://stackoverflow.com/questions/25879449/javascript-if-x-y-z