一:循环比较
Array .prototype.unique1 = function () {
var res = [this [0 ]];
for (var i = 1 ; i < this .length; i++) {
var repeat = false ;
for (var j = 0 ; j < res.length; j++) {
if (this [i] === res[j]) {
repeat = true ;
break ;
}
}
if (!repeat) {
res.push(this [i]);
}
}
return res;
}
var arr = [1 , 'a' , 'a' , 'b' , 'd' , 'e' , 'e' , 1 , 0 ]
alert(arr.unique1());
二:indexof方法
Array .prototype.unique2 = function () {
var n = [];
for (var i = 0 ; i < this .length; i++)
{
if (n.indexOf(this [i]) == -1 ){
n.push(this [i]);
}
}
return n;
}
三:方法比上面的方法效率要高,但是改变了数组的排列顺序
Array .prototype.unique3 = function () {
this .sort();
var res = [this [0 ]];
for (var i = 1 ; i < this .length; i++) {
if (this [i] !=== res[res.length - 1 ]) {
res.push(this [i]);
}
}
return res;
}
var arr = [1 , 'a' , 'a' , 'b' , 'd' , 'e' , 'e' , 1 , 0 ]
alert(arr.unique3());
四:推荐写法
Array .prototype.unique4 = function () {
var res = [];
var json = {};
for (var i = 0 ; i < this .length; i++) {
if (!json[this [i]]) {
res.push(this [i]);
json[this [i]] = 1 ;
}
}
return res;
}
var arr = [112 , 112 , 34 , '你好' , 112 , 112 , 34 , '你好' , 'str' , 'str1' ];
alert(arr.unique4());