Can you compare multiple variables to see if they all equal the same value in JS?

天涯浪子 提交于 2020-04-27 06:19:28

问题


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;
}

and this:

if (die1 == die2 == die3 == die4 == die5) {
    yahtzeeQualify == true;
}

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...


回答1:


Are either of these valid?

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.

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

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]))



回答2:


Solution with the Array.reduce:

var values = [die1, die2, die3, die4, die5];

var yahtzeeQualify = values.reduce(function(memo, element) {
   return element === values[0];
});



回答3:


The 1st one is what you want, but it's messed up. You want && not &

The 2nd one is logically wrong.

To do it with an array

yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })


来源:https://stackoverflow.com/questions/29711396/can-you-compare-multiple-variables-to-see-if-they-all-equal-the-same-value-in-js

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