// 数组去重
Array.prototype.unique1 = function()
{
var n = []; //一个新的临时数组
for(var i = 0; i < this.length; i++) //遍历当前数组
{
//如果当前数组的第i已经保存进了临时数组,那么跳过,
//否则把当前项push到临时数组里面
if (n.indexOf(this[i]) == -1) n.push(this[i]);
}
return n;
}
Array.prototype.unique2 = function()
{
var n = {}, r = [], len = this.length, val, type;
for (var i = 0; i < this.length; i++) {
val = this[i];
type = typeof val;
if (!n[val]) {
n[val] = [type];
r.push(val);
} else if (n[val].indexOf(type) < 0) {
n[val].push(type);
r.push(val);
}
}
return r;
}
Array.prototype.unique3 = function()
{
var n = [this[0]]; //结果数组
for(var i = 1; i < this.length; i++) //从第二项开始遍历
{
//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
//那么表示第i项是重复的,忽略掉。否则存入结果数组
if (this.indexOf(this[i]) == i) n.push(this[i]);
}
return n;
}
// 第4种方式只能针对于共一种数据类型的数组进行处理,
// 因为不同类型的数组数据在sort的处理后的返回有问题
Array.prototype.unique4 = function()
{
this.sort(function compare(a,b){return a-b;});
var re=[this[0]];
for(var i = 1; i < this.length; i++)
{
if( this[i] !== re[re.length-1])
{
re.push(this[i]);
}
}
return re;
}
var a = [1,2,3,'1',2,'3',1,31,22,3,'1',12,'3',31,1,1232,343,'124',2,'23',241,51,62,93,'41',462,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,1,2,3,'1',2,'3',1,];
var b = [1,2,3,4,5,12,1,2,3,2,4,6,3,4,2];
a.unique1();
a.unique2();
a.unique3();
b.unique4();