你可以比较多个变量,看看它们在 JS 中是否都等于相同的值?

2022-01-25 00:00:00 compare equals javascript

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

解决方案

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

相关文章