我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?

['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false

当前回答

这个作品。通过使用prototype在Array上创建一个方法。

if (Array.prototype.allValuesSame === undefined) {
  Array.prototype.allValuesSame = function() {
    for (let i = 1; i < this.length; i++) {
      if (this[i] !== this[0]) {
        return false;
      }
    }
    return true;
  }
}

这样调用它:

let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame();     // false

其他回答

function isUniform(array) {   
  for (var i=1; i< array.length; i++) {
    if (array[i] !== array[0]) { return false; }
  }

  for (var i=1; i< array.length; i++) {
    if (array[i] === array[0]) { return true; }
  }
}

对于第一个循环;当它检测到不均匀时,返回"false" 第一个循环运行,如果返回false,就有"false" 当它不返回false时,它意味着将会有true,所以我们做第二个循环。当然,在第二个循环中我们会得到"true"(因为第一个循环发现它不是假的)

你可以使用Array.prototype让这一行代码做你想做的事情。每一个对象。和ES6箭头函数:

const all = arr => arr.every(x => Object.is(arr[0], x));

通过加入数组创建一个字符串。 通过重复给定数组的第一个字符创建字符串 匹配两个字符串

函数checkArray(数组){ 返回array.join("") == array[0].repeat(array.length); } console.log('数组:(,,,):”+ checkArray ([' a ', ' ', ' ', ' '))); console.log('数组:[a, a, b, a]: ' + checkArray ([' a ', ' ', ' b ', ' ')));

这样你就完成了!

**// Logical Solution:- Declare global array and one variable(To check the condition) whether all element of an array contains same value or not.**

    var arr =[];
    var isMatching = false;

    for(var i=0;i<arr.length;i++){
            if(String(arr[i]).toLowerCase()== "Your string to check"){
                isMatching=true;
                // Array has same value in all index of an array
            }
            else{
                isMatching=false;
                // Array Doesn't has same value in all index of an array
                break;
            }
        }
    // **Check isMatching variable is true or false**

        if(isMatching){ // True
            //If Array has same value in all index, then this block will get executed
        }
        else{ //False
            //If Array doesn't has same value in all index, then this block will get executed
        }

在PHP中,有一个非常简单的解决方案,一行方法:

(count(array_count_values($array)) == 1)

例如:

$arr1 = ['a', 'a', 'a', 'a'];
$arr2 = ['a', 'a', 'b', 'a'];


print (count(array_count_values($arr1)) == 1 ? "identical" : "not identical"); // identical
print (count(array_count_values($arr2)) == 1 ? "identical" : "not identical"); // not identical

这是所有。