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

查看:71
本文介绍了Javascript if(x == y == z):的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个随机数(在这种情况下,介于1到7之间,但这并不重要).我想检查我是否通过使用

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
}

问题在于,当 x == y z == 1 x == y == z 时,返回true.如何检查x,y和z是否实际上获得了相同的值?示例: 5 == 5 == 1 将返回true,如何专门检查 5 == 5 == 5 ?(不包括 5 == 5 == 1 )

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)

推荐答案

通过适当的比较:

x === y && y === z
// due to transitivity, if the above expression is true, x === z must be true as well


x == y == z 的实际评估为

(x == y) == z

即您正在比较 true == z false == 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

问题在于,当 x == y z == 1 时, x == y == z 将返回true.

The problem is that when x==y and z==1, x==y==z will return true.

是的,因为 x == y 将是 true ,所以您比较 true == 1 . true 将转换为数字 1 ,而 1 == 1 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.

这篇关于Javascript if(x == y == z):的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆