js数组去掉重复元素的范例参考

发布时间:2020-06-06编辑:脚本学堂
本文介绍下,在js中去除数组中重复元素的一个例子,有需要的朋友,参考学习下吧。

js去除数组中的重复元素,代码:

<script>
Array.prototype.uniq = function() {  
var temp = {}, len = this.length;

for(var i=0; i < len; i++)  {  
    if(typeof temp[this[i]] == "undefined") {
    temp[this[i]] = 1;
    }  
}  
this.length = 0;
len = 0;
for(var i in temp) {  
    this[len++] = i;
}  
return this;  
}  
   
var a = ["sss","aaa","sss",4,2,3,1,1,"sss","aaa","sss",4,2,3,1,1
,"sss","aaa","sss",4,2,3,1,1,"sss","aaa","sss",4,2,3,1,1
,"sss","aaa","sss",4,2,3,1,1,"sss","aaa","sss",4,2,3,1,1
,"sss","aaa","sss",4,2,3,1,1,"sss","aaa","sss",4,2,3,1,1];  
var b = [2,3,5,7]; 
//-------时间测试开始----
start = new Date().getTime(); 
var c = a.concat(a).concat(b).concat(a).concat(b).concat(a)
.concat(b).concat(a).concat(b).concat(a).concat(b)
.concat(a).concat(b).concat(b).concat(a).concat(b).uniq(); 

document.write(c + " 长度 " + c.length); 
end = new Date().getTime();
    
document.write(" 耗时:" + (end - start) + "ms")
//------时间测试结束------
//IE结果:sss,aaa,4,2,3,1,5,7 长度 8 耗时:15ms
//FF结果:sss,aaa,4,2,3,1,5,7 长度 8 耗时:2ms
</script>