如何在javascript代码中,判断数组中是否有重复值呢?
这里分享三个简单方法,供大家参考。
1,JS 判断数组重复值的方法一:
var ary = new Array("111","22","33","111"); 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; } }
2,JS 判断数组重复值的方法二:
var ary = new Array("111","22","33","111"); var nary=ary.sort(); for(var i=0;i<ary.length;i++){ if (nary[i]==nary[i+1]){ alert("数组中有重复内容:"+nary[i]); } }
3,JS 判断数组重复值的方法三:
function isRepeat(arr){ var hash = {}; for(var i in arr) { if(hash[arr[i]]) return true; hash[arr[i]] = true; } return false; }