如何判断JavaScript 数组含有重复值
1个回答
展开全部
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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询