您可以比较多个变量以查看它们在JS中是否都等于相同的值吗? [英] Can you compare multiple variables to see if they all equal the same value in JS?
问题描述
使用Javascript,我试图查看在给定的时间是否5个不同的变量都包含相同的值。该值可能是6项中的1项,但是无论它是哪个值,我都需要查看它们是否都相同。我已经尝试过:
Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
,并且:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
以下任一有效吗?如果是这样,我的代码可能在其他地方出错了。如果没有,我将非常感谢您的帮助。我在名为dieArray的数组中也有这些变量,如下所示:
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
学习通过数组执行此操作的方法很酷,但是如果不是这样顺理成章吧。我会继续尝试自己想办法,但是直到现在我还是被困住...
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
推荐答案
这两个都有效吗?
Are either of these valid?
它们是有效的(因为这是可执行代码)但是他们不执行您想要的计算。您要使用逻辑与(&
)不是按位AND。
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&
) not a bitwise AND.
第二个错误。您遇到强制类型问题,最终将 die1
与 true
或 false
。
The second one is just wrong. You run into type coercion issues and end up comparing die1
to either true
or false
.
通过数组学习实现此方法很酷
It would be cool to learn a way to do this via the array
您可以使用 Array#every
并比较每个元素是否等于第一个元素:
You can use Array#every
and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
这篇关于您可以比较多个变量以查看它们在JS中是否都等于相同的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!