检查多个数组值是否相等

时间:2022-02-09 14:09:15

So I have an array which has 3 possible values: 0, 1 or 2

所以我有一个数组有3个可能的值:0 1或2

var a = [0,0,0];

I want to check if a[0], a[1], and a[2] all have the equal value of "1" or "2". How can I do this?

我想检查[0][1]和[2]是否都等于1或2。我该怎么做呢?

So 0,0,0 would return false, 1,2,1 false, but 1,1,1 or 2,2,2 would be true.

所以0 0 0会返回false, 1 2 1 1 1 1 1或2 2 2 2是正确的。

4 个解决方案

#1


3  

Try this:

试试这个:

function checkArray(array){
    var firstElement = array[0];
    if(!firstElement) return false;

    var result = true;

    array.forEach(function(elem){
        if(elem != firstElement) result = false;
    });

    return result;
}

#2


2  

The regex solution was slow as shown in http://jsperf.com/looping-vs-regex. SO came up with this.

regex解决方案很慢,如http://jsperf.com/looping-vs-regex所示。所以我想到了这个。

function checkArr(arr){
   var f = arr[0];
   if(f == 0) return false;
   for(var i = 0; i < arr.length; i++)
      if(arr[i] != f) return false;
   return true;
}

#3


0  

Try this:

试试这个:

var validate = function(arr) {
    var s = 0;
    var i = l = arr.length;
    while(i --)
        s += arr[i];
    return l === s || (2 * l) === s;
};

console.log(validate([0,0,0]));//false
console.log(validate([1,2,1]));//false
console.log(validate([2,2,2]));//true
console.log(validate([1,1,1]));//true
console.log(validate([2,2,2,2,2]));//true

#4


0  

Another apporach, without looping or regexes:

另一个apporach,没有循环或regexes:

var arr = [1,2,1];
arr.every(function (el) {
  return (el === 1 || el === 2) && el === arr[0];
})

Or, with .some instead of .every:

或者,用。some代替。every:

!arr.some(function (el) {
  return (el !== 1 && el !== 2) || el !== arr[0];
})

#1


3  

Try this:

试试这个:

function checkArray(array){
    var firstElement = array[0];
    if(!firstElement) return false;

    var result = true;

    array.forEach(function(elem){
        if(elem != firstElement) result = false;
    });

    return result;
}

#2


2  

The regex solution was slow as shown in http://jsperf.com/looping-vs-regex. SO came up with this.

regex解决方案很慢,如http://jsperf.com/looping-vs-regex所示。所以我想到了这个。

function checkArr(arr){
   var f = arr[0];
   if(f == 0) return false;
   for(var i = 0; i < arr.length; i++)
      if(arr[i] != f) return false;
   return true;
}

#3


0  

Try this:

试试这个:

var validate = function(arr) {
    var s = 0;
    var i = l = arr.length;
    while(i --)
        s += arr[i];
    return l === s || (2 * l) === s;
};

console.log(validate([0,0,0]));//false
console.log(validate([1,2,1]));//false
console.log(validate([2,2,2]));//true
console.log(validate([1,1,1]));//true
console.log(validate([2,2,2,2,2]));//true

#4


0  

Another apporach, without looping or regexes:

另一个apporach,没有循环或regexes:

var arr = [1,2,1];
arr.every(function (el) {
  return (el === 1 || el === 2) && el === arr[0];
})

Or, with .some instead of .every:

或者,用。some代替。every:

!arr.some(function (el) {
  return (el !== 1 && el !== 2) || el !== arr[0];
})