我想扫描JS数组并确定所有元素是否唯一,或者数组是否包含重复项.
例子:
my_array1 = [1,2,3] my_array2 = [1,1,1]
我想得到这样的结果:
my_array1 must be return true,because this array element is unique and array2 must be return false,because this array element is not unique
我怎么去写这个方法?
解决方法
如果你想检查唯一性,你也可以这样做.如评论所述,我不断言这是唯一最好的选择.下面有一些很好的答案.
var arr = [2,3,4,6,7,8,9];
var uniq = []; // we will use this to store the unique numbers found
// in the process for doing the comparison
var result = arr.slice(0).every(function(item,index,array){
if(uniq.indexOf(item) > -1){
// short circuit the loop
array.length=0; //(B)
return false;
}else{
uniq.push(item);
return true;
}
});
result --> true
arr.slice(0)创建一个数组的临时副本,在其上进行实际处理.这是因为当满足唯一性标准时,我清除数组(B)以使循环短路.这将确保处理一旦满足标准就停止.
如果我们将它作为Array实例上的方法公开,那么会更好.
所以我们可以这样做[1,5,7] .isUnique();
添加以下代码段,您就可以开始了
Array.prototype.isUnique = function() {
var uniq = [];
var result = this.slice(0).every(function(item,arr) {
if (uniq.indexOf(item) > -1) {
arr.length = 0;
return false;
} else {
uniq.push(item);
return true;
}
});
return result;
};
arr.isUnique() --> true
DEMO