1 . 只做判断无返回数组时,可用如下方法:
function isRepeat(arr){
var hash = {}, type = '';
for(var i in arr){
type = Object.prototype.toString.call(arr[i]);
if(hash[arr[i] + type]){
return true;
}
hash[arr[i] + type] = true;
}
return false;
}
调用方法:
var arr = [1234567, 123, 123, 1, '1'];
$("#id").val(isRepeat(arr));
2 . 需返回结果时,可用如下方法:
function isRepeatReturn(arr){
var hash = {}, result = [], type = '';
for(var i in arr){
type = Object.prototype.toString.call(arr[i]);
if ( !hash[arr[i] + type] ) {
hash[arr[i] + type] = true;
result.push(arr[i]);
}
}
return result;
}
或者:
if (!Array.prototype.unique) {
Array.prototype.unique = function () {
var hash = {}, result = [], type = '';
for (var i = 0; i < this.length; i++) {
type = Object.prototype.toString.call(this[i]);
if ( !hash[this[i]+ type] ) {
hash[this[i]+ type] = true;
result.push(this[i]);
}
}
return result;
};
}
调用方法:
var arr = [0, 1, '1', true, 5, true, false, undefined, undefined, null, null];
$("#result").val(isRepeatReturn(arr));
$("#result").val(arr.unique());

本文介绍两种JavaScript方法来检查数组中是否存在重复元素。一种方法仅返回布尔值,另一种则返回去除重复后的数组。这两种方法都利用了哈希表来提高效率。
1113

被折叠的 条评论
为什么被折叠?



