javascript的4种数组去重(包含 es6 去重写法)
1: 第一种
Array.prototype.unique1= function(){
var newArr =[];
for(var i=0; i< this.length; i++){
if( newArr.indexof(this[i]) == -1 ){
newArr.push(this[i])
}
}
return newArr
}
2: 第二种
Array.prototype.unique2 = function(){
var newArr =[] , obj = {} ;
for(var i=0; i< this.length; i++){
if( !obj[this[i]] ){
obj[this[i]] = true;
newArr.push(this[i])
}
}
return newArr;
}
3: 第三种方式
Array.prototype.unique3 = function(){
var newArr =[this[0]] ;
for(var i=1; i< this.length; i++){
if(this.indexof(this[i]) == i ) newArr.push(this[i])
}
return newArr;
}
4: 第四种方式 // 这是es6种的最新写法,如果你的程序支持es6,你可大胆使用
newArr = [...new set(oldArr)]