如题所述
javascript判断一个数组中是否有重复值的三种方法:
判断重复方法一,转为字符串 进行比较:
var ary = new Array("aaa","cc","dd","aaa");
var s = ary.join(",")+",";
for(var i=0;i<ary.length;i++) {
if(s.replace(ary[i]+",","").indexOf(ary[i]+",")>-1) {
alert("数组中有重复元素:" + ary[i]);
break;
}
}
判断重复方法二,数组排序,再比较相邻的值:
var ary = new Array("bbb","cc","dd","bbb");
var nary=ary.sort();
for(var i=0;i<ary.length;i++){
if (nary[i]==nary[i+1]){
alert("数组重复内容为:"+nary[i]);
}
}
判断重复方法三,自定义函数方法判断重复:
function isRepeat(arr){
var hash = {};
for(var i in arr) {
if(hash[arr[i]])
return true;
hash[arr[i]] = true;
}
return false;
}
判断重复方法一,转为字符串 进行比较:
var ary = new Array("aaa","cc","dd","aaa");
var s = ary.join(",")+",";
for(var i=0;i<ary.length;i++) {
if(s.replace(ary[i]+",","").indexOf(ary[i]+",")>-1) {
alert("数组中有重复元素:" + ary[i]);
break;
}
}
判断重复方法二,数组排序,再比较相邻的值:
var ary = new Array("bbb","cc","dd","bbb");
var nary=ary.sort();
for(var i=0;i<ary.length;i++){
if (nary[i]==nary[i+1]){
alert("数组重复内容为:"+nary[i]);
}
}
判断重复方法三,自定义函数方法判断重复:
function isRepeat(arr){
var hash = {};
for(var i in arr) {
if(hash[arr[i]])
return true;
hash[arr[i]] = true;
}
return false;
}
温馨提示:答案为网友推荐,仅供参考