标签:nbsp 数组 lis -- 循环 var [] 总结 continue
【数组去重】本文一共总结了5种方法:
//方法一:sort方法
var ary = [1, 4, 2, 3, 1, 2, 2, 3, 3, 2, 5, 2, 1, 2];
Array.prototype.rmSame = function () {
var ary = this.sort(function (a, b) {
return a - b
});
for (var i = 0; i < ary.length; i++) {
if (ary[i] === ary[i + 1]) {
ary.splice(i, 1);
i--;
}
}
return ary;
};
console.log(ary.rmSame());
//方法二,双循环比较
var ary1 = [1, 4, 2, 3, 1, 2, 2, 3, 3, 2, 5, 2, 1, 2];
Array.prototype.rMsame = function () {
for(var i=0;i<this.length;i++){
var oLis=this[i];
for(var j=i+1;j<this.length;j++){
if(oLis===this[j]){
this.splice(j,1);
j--;
}
}
}
return this;
};
console.log(ary1.rMsame());
//方法三:键值对
var ary = [1, 2, 1, 2, 1, 2, 1, 4, 5, 63, 2, 5, 432, 24];
Array.prototype.rmSome = function () {
var obj={};
for(var i=0;i<this.length;i++){
var cur=this[i];
if(obj[cur]==cur){
this[i]=this[this.length-1];
this.length--;
i--;
continue;
}
obj[cur]=cur;
}
return this;
};
console.log(ary.rmSome());
//方法四 新数组
var ary1=[];
for(var i=0; i<ary.length; i++){
/!*if(ary1.indexOf(ary[i])==-1){
ary1.push(ary[i]);
}else{
ary.splice(i,1);
i--;
}*!/
if(ary1.indexOf(ary[i])==-1){
ary1.push(ary[i]);
}
}
//方法五 可以记录对象的数组去重
var obj={};
for(var i=0; i<ary.length; i++){
var cur=ary[i];
if(obj[cur]){
obj[cur]++;
}else{
obj[cur]=1;
}
}
var ary=[];
for(var attr in obj){
ary.push(attr);
}
&&&&数组去重方法总结&&&&&
标签:nbsp 数组 lis -- 循环 var [] 总结 continue
原文地址:http://www.cnblogs.com/HKCC/p/6060616.html