Javascript if (x==y==z): [duplicate]

流过昼夜 提交于 2021-02-17 05:10:57

问题


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 and z==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

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