js判断数组中是否有重复元素
方法一:正则
var ary = new Array("111","ff","222","aa","222"); alert(mm(ary)) // 验证重复元素,有重复返回true;否则返回false function mm(a) { return /(\x0f[^\x0f]+)\x0f[\s\S]*\1/.test("\x0f"+a.join("\x0f\x0f") +"\x0f"); }
方法二:通过字符串查找
function isRepeat() { 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; } } }
方法三:通过数组排序,比较临近元素
function isRepeat() { 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]); } } }
方法四:通过哈希
function isRepeat(arr) { var hash = {}; for (var i in arr) { if (hash[arr[i]]){ return true; } hash[arr[i]] = true; } return false; }