JavaScript去掉数组中的重复元素_javascript技巧

WBOY
Release: 2016-05-16 18:12:10
Original
1105 people have browsed it

在写程序过程中,经常会遇到去除数组中重复元素的需求。要实现这个功能其实并不难。
我们可以用一个两重循环来实现,对于小的数组,这样做当然并无不妥。
但如果我们的数组比较大,里面的元素有上万个。那么用两重循环,效率是极为低下。
下面我们就用js的特性,编写一个高效去除数组重复元素的方法。

复制代码代码如下:



输出结果:
9,1,3,8,7,6,5,4
js数组去重就是把数组中重复的元素去掉:
复制代码代码如下:

Array.prototype.delRepeat=function(){
var newArray=new Array();
var len=this.length;
for (var i=0;i for(var j=i+1;j if(this[i]===this[j]){
j=++i;
}
}
newArray.push(this[i]);
}
return newArray;
}

  但是很明显这里有for循环内嵌了另一个for循环,在大数据量下肯定非常耗时!效率低下!经过查找和高人指点优化了一个新方法:
复制代码代码如下:

Array.prototype.delRepeat=function(){
var newArray=[];
var provisionalTable = {};
for (var i = 0, item; (item= this[i]) != null; i++) {
if (!provisionalTable[item]) {
newArray.push(item);
provisionalTable[item] = true;
}
}
return newArray;
}

  就是使用一个临时的provisionalTable对象,将数组的值作为provisionalTable对象的键值,如果相应的值不存在就将这个数组的值push到新数组中。
  效率是提高了,但是有个bug,就是假设数组中换用可转换的数字和字符串,比如数组[6,"6"]这时候就好被去掉一个。悲剧,同时求解决方法。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn