我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
当前回答
通过加入数组创建一个字符串。 通过重复给定数组的第一个字符创建字符串 匹配两个字符串
函数checkArray(数组){ 返回array.join("") == array[0].repeat(array.length); } console.log('数组:(,,,):”+ checkArray ([' a ', ' ', ' ', ' '))); console.log('数组:[a, a, b, a]: ' + checkArray ([' a ', ' ', ' b ', ' ')));
这样你就完成了!
其他回答
简单的一行解决方案,只需将其与充满第一个条目的数组进行比较。
if(arr.join('') === Array(arr.length).fill(arr[0]).join(''))
通过加入数组创建一个字符串。 通过重复给定数组的第一个字符创建字符串 匹配两个字符串
函数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
}
你可以使用数组。每个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;
同样适用。
下划线_。isEqual(object, other)函数似乎可以很好地用于数组。当它检查是否相等时,数组中项目的顺序很重要。见http://underscorejs.org/ # isEqual。