利用indexOf 和 forEach 实现
Array.prototype.distinct = function(){
var arr = this, result = [];
arr.forEach(function(item,index,arr){
var bool = arr.indexOf(item, index+1)
if(bool === -1){
result.push(item);
}
})
return result;
}
var a = [1,1,1,2,2,2,3,3,3,4,4,4,1,2,3,4]
var b = a.distinct();
console.log(b);
利用对象属性不同的特性实现
Array.prototype.distinct1 = function(){
var arr = this, i, result = [], obj = {},len = arr.length;
for(i=0;i<len;i++){
if(!obj[arr[i]]){
obj[arr[i]] = 1;
result.push(arr[i]);
}
}
return result;
}
var a = [1,2,3,4,2,3,1,3,4,5,6,1,1,1,1,1]
var b = a.distinct1();
console.log(b.toString())