问题描述:

I was wondering if there was a quick way to test the equality of more than two values in js. Something similar to (= 6 6 6).

In the console, I tried things like...

1 == 1 == 1 == 1

true

2 == 2 == 2 == 2

false

0 == 0 == 0

false

0 == 0 == 0 == 0

true

...which was amusing, but also puzzling.

Is there a quick way of doing this in js?

Thanks.

网友答案:

The reason you got unexpected behavior is because we need to adjust your expectations in js a bit ;) 2 == 2 == 2 == 2 does 3 comparisons, all from left to right. The first comparison is the leftmost 2 == 2, which evaluates to true. After that we get the result of the first comparison being compared to (what is in this case) the 3rd 2. Ie, true === 2, which is false. And finally, we get false === 2, which is also false.

It might help to visualize it as such:

(((2 == 2) == 2) == 2)

I think in general a === b && b === c might be what you're looking for.

EDIT: Ah, and sorry I keep switching out the == for ===. It's just habit. And it's a habit I'd recommend. the === operator doesn't do type casting, so it evaluates the value proper, not a casted version of the value.

网友答案:

It's because true == 1 but true != 2

You can try:

function isEquals() {
 var flag = true;
 for(var i=1; i<arguments.length; i++) flag = flag && (arguments[i] == arguments[0]);
  return flag;
}
isEquals(2,2,2); // true

or:

function isEquals() {
 var ar = arguments;
 return Array.prototype.every.call(arguments, function(a){return a==ar[0];});
}
网友答案:

Yes you can, but you need to use the "Logical Operators" like the && or || to check more than 1 statement like (x<1 && y>0). You can use this as a quick easy reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

网友答案:

If you have more than three values, it might be more convenient to create a function for use on an array:

function allEqual(arr) {
    return arr.every(function (x, i) {
        return i === 0 || x === arr[i - 1];
    });
}

allEqual([1, 1, 1])

ES6:

function allEqual(...arr) {
    return arr.every((x, i) => i === 0 || x === arr[i - 1]);
}

allEqual(1, 1, 1)
网友答案:

As an addition to @vp_arth's answer you could even add a method to the Array prototype

Array.prototype.isHomogeneous = function(){
    return Array.prototype.every.call(this, function(c,i,a){ return c === a[0];})
}

So you could do

[1,2,3].isHomogeneous() = false

[1,1,1].isHomogeneous() = true

相关阅读:
Top