js判斷數組裡是否有重複元素的方法
阿新 • • 發佈:2019-02-12
// 方法一,正則判斷------本人已經測試過,其他的沒有測試過。
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");
}
// 方法二,通過陣列排序,比較臨近元素,可指出重複的元素
var ary = newArray("111","22","33","111","22");
var nary = ary.sort();
for(var i = 0; i < nary.length - 1; i++)
{
if (nary[i] == nary[i+1])
{
alert("重複內容:" + nary[i]);
}
}
// 方法三,通過字串查詢
var ary = newArray("111","22","33","111","22");
var s = ary.join(",") +",";
for(var i = 0; i < ary.length; i++)
{
if(s.replace(ary[i] + ",", "").indexOf(ary[i] +",") > -1)
{
alert("重複內容:" + ary[i]);
}
}
// 方法四,通過雜湊
var ary = newArray("111","22","33","111","22");
alert(isRepeat(ary));
// 驗證重複元素,有重複返回true;否則返回false
function isRepeat(arr) {
var hash = {};
for(var i in arr) {
if(hash[arr[i]])
{
return true;
}
// 不存在該元素,則賦值為true,可以賦任意值,相應的修改if判斷條件即可
hash[arr[i]] = true;
}
return false;
}
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");
}
// 方法二,通過陣列排序,比較臨近元素,可指出重複的元素
var ary = newArray("111","22","33","111","22");
var nary = ary.sort();
for(var i = 0; i < nary.length - 1; i++)
{
if (nary[i] == nary[i+1])
{
alert("重複內容:" + nary[i]);
}
}
// 方法三,通過字串查詢
var ary = newArray("111","22","33","111","22");
var s = ary.join(",") +",";
for(var i = 0; i < ary.length; i++)
{
if(s.replace(ary[i] + ",", "").indexOf(ary[i] +",") > -1)
{
alert("重複內容:" + ary[i]);
}
}
// 方法四,通過雜湊
var ary = newArray("111","22","33","111","22");
alert(isRepeat(ary));
// 驗證重複元素,有重複返回true;否則返回false
function isRepeat(arr) {
var hash = {};
for(var i in arr) {
if(hash[arr[i]])
{
return true;
}
// 不存在該元素,則賦值為true,可以賦任意值,相應的修改if判斷條件即可
hash[arr[i]] = true;
}
return false;
}