对于数组去重,有以下三种方法:
第一种:
Array.prototype.unique1 = function(){
var newArray = [this[0]];//结果数组
for(var i = 1; i < this.length; i++){
if(newArray.indexOf(this[i]) == -1){
newArray.push(this[i]);
}
}
return newArray;
}
第二种:
Array.prototype.unique2 = function(){
var newArray = [this[0]];//结果数组
for(var i = 1; i < this.length; i++){
if(this.indexOf(this[i]) == i){
newArray.push(this[i]);
}
}
return newArray;
}
第三种:
Array.prototype.unique3 = function(){
var arrayMap = {}, newArray = [];
for(var i = 0; i < this.length; i++){
if(!arrayMap[this[i]]){
arrayMap[this[i]] = true;
newArray.push(this[i]);
}
}
return newArray;
}