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

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

当前回答

它的简单。 创建一个函数并传递一个参数。 在该函数中,将第一个索引复制到一个新变量中。 然后创建一个for循环,循环遍历数组。 在循环中,创建一个while循环,检查新创建的变量是否等于循环中的所有元素。 如果它在for循环结束后返回true,则在while循环中返回false。

function isUniform(arra){
    var k=arra[0];
    for (var i = 0; i < arra.length; i++) {
        while(k!==arra[i]){
            return false;
        }
    }
    return true;
}

其他回答

each()函数检查数组中的所有元素

    const checkArr = a => a.every( val => val === a[0] )
    checkArr(['a','a','a'])  // true 
     

这个作品。通过使用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

现在您可以使用集合轻松地做到这一点。

Let a= ['a', 'a', 'a', 'a'];/ /正确的 Let b =['a', 'a', 'b', 'a'] console.log(新组(a)。Size === 1); console.log(新组(b)。Size === 1);

你可以用这个:

function same(a) {
    if (!a.length) return true;
    return !a.filter(function (e) {
        return e !== a[0];
    }).length;
}

该函数首先检查数组是否为空。如果是的话,它的值是相等的。 否则,它会过滤数组并获取与第一个不同的所有元素。如果没有=>这样的值,则数组只包含相等的元素,否则不包含。

**// 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
        }