我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
当前回答
我喜欢的另一个很酷的解决方案是使用异或运算符:
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
其他回答
这个作品。通过使用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
我认为最简单的方法是创建一个循环来比较每个值和下一个值。只要“链”中有断点,它就会返回false。如果第一个元素等于第二个元素,第二个元素等于第三个元素,以此类推,那么我们可以得出这样的结论:数组中的所有元素彼此相等。
给定一个数组data[],那么你可以使用:
for(x=0;x<data.length - 1;x++){
if (data[x] != data[x+1]){
isEqual = false;
}
}
alert("All elements are equal is " + isEqual);
**// 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
}
这可能会起作用,你也可以使用注释代码,这也适用于给定的场景。
函数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 ();
你可以使用数组。每个if支持:
var equals = array.every(function(value, index, array){
return value === array[0];
});
循环的替代方法可以是类似sort的东西
var temp = array.slice(0).sort();
var equals = temp[0] === temp[temp.length - 1];
或者,如果项目像问题,一些肮脏的东西,比如:
var equals = array.join('').split(array[0]).join('').length === 0;
同样适用。