你可以比较多个变量,看看它们在 JS 中是否都等于相同的值? [英] Can you compare multiple variables to see if they all equal the same value in JS?

查看:28
本文介绍了你可以比较多个变量,看看它们在 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...

解决方案

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

这篇关于你可以比较多个变量,看看它们在 JS 中是否都等于相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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