Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...