我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
当前回答
你可以使用Array.prototype让这一行代码做你想做的事情。每一个对象。和ES6箭头函数:
const all = arr => arr.every(x => Object.is(arr[0], x));
其他回答
你可以使用Array.prototype让这一行代码做你想做的事情。每一个对象。和ES6箭头函数:
const all = arr => arr.every(x => Object.is(arr[0], x));
**// 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
}
我喜欢的另一个很酷的解决方案是使用异或运算符:
console.log([5,5,5,5].reduce((a,b)=>a^b) == 0)
>> true
console.log([5,5,5,4].reduce((a,b)=>a^b) == 0)
>> false
您可以将Array转换为Set。如果Set的大小等于1,则数组中的所有元素都相等。
function allEqual(arr) {
return new Set(arr).size == 1;
}
allEqual(['a', 'a', 'a', 'a']); // true
allEqual(['a', 'a', 'b', 'a']); // false
这可能会起作用,你也可以使用注释代码,这也适用于给定的场景。
函数isUniform () { var arrayToMatch = [1,1,1,1,1]; var temp = arrayToMatch[0]; console.log(临时); /*返回arrayToMatch.every(函数(检查){ 返回检查== temp; }); * / var bool; arrayToMatch.forEach(函数(检查){ Bool =(check == temp); }) console.log (bool); } isUniform ();