Array.prototype.unique1 = function(){//有局限性,1,“1”的情况会被去重,因为存入临时对象时,数组中的值被统一转换成了字符串
var obj = {},newArr = [];
for(var i=0;i<this.length;i++){
if(!obj[this[i]]){
obj[this[i]] = true;
newArr.push(this[i]);
}
}
return newArr;
}
/*arr = arr.unique1();
console.log(arr);*/
Array.prototype.unique2 = function(){
var newArr = []; //临时数组
for(var i=0;i<this.length;i++){
if(newArr.indexOf(this[i]) == -1){
newArr.push(this[i]);
}
}
return newArr;
}
/*arr = arr.unique2();
console.log(arr);*/
Array.prototype.unique3 = function(){
var newArr = [];
for(var i=0;i<this.length;i++){
if(this.indexOf(this[i]) == i){
newArr.push(this[i]);
}
}
return newArr;
}
/*arr = arr.unique3();
console.log(arr);*/
Array.prototype.unique4 = function(){ //改变了数组的顺序
this.sort();
var newArr=[this[0]];
for(var i = 1; i < this.length; i++)
{
if( this[i] !== newArr[newArr.length-1])
{
newArr.push(this[i]);
}
}
return newArr;
}
arr = arr.unique4();
console.log(arr);
这四个方法思路基本都是一样的,只是写法不同