var arr=[‘apple’, ‘strawberry’, ‘banana’, ‘pear’, ‘apple’, ‘orange’, ‘orange’, ‘strawberry’,1,3,6,3];
arr.filter(function(e,i,self){
return self.indexOf(e)==i;
})//["apple", "strawberry", "banana", "pear", "orange", 1, 3, 6]
(function unique1(){
var n = []; //一个新的临时数组
for(var i = 0; i < arr.length; i++){
if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
}
return n;
})(arr)
(function unique2(){
var n=[arr[0]];
for(var i=1;i<arr.length;i++){
if(arr.indexOf(arr[i])==i)n.push(arr[i]);
}
return n;
})(arr)
Array.prototype.unique2 = 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.unique2());
新技能
var array=[1,2,3,4,5,2,3,2,3,"","","apple",2,"apple"];
function f(array){
return [...new Set(array)]
}
f(array)//[1, 2, 3, 4, 5, "", "apple"]