标签:
javascript去除数组中的重复元素
//方法1,循环数组,判断当前元素是否已存在临时数组内
Array.prototype.removeRepeat = function(){
var arr = this;
var tmp = [arr[0]];
for(var i=1; i<arr.length; i++){
if(tmp.indexOf(arr[i])>-1){
continue;
}
tmp.push(arr[i]);
}
return tmp;
}
//方法2,数组先进行排序,再循环数组,判断当前元素是否已存在临时数组内
Array.prototype.removeRepeat = function(){
var arr = this.sort();
var tmp = [arr[0]];
for(var i=1; i<arr.length; i++){
if(arr[i] && arr[i]!=arr[i-1]){
tmp.push(arr[i]);
}
}
return tmp;
}
var arr = ["ad","sd","as","sd","sc","we"];
arr.removeRepeat(); //输出 ["ad","sd","as","sc","we"]
标签:
原文地址:http://www.cnblogs.com/cyj7/p/4571450.html