var array = [1,'1',1,'1',true,'true',2,3,2];
要求结果为:[1,'1',true,'true',2,3];顺序无要求,但时间复杂度尽可能低,最好是O(n)。给出答案前千万要试运行一遍呐,网上的例子都不行。
这个运行了是你要的结果,网上给的答案,你试试行不
var array = [1,'1',1,'1',true,'true',2,3,2];
Array.prototype.distinct = function(){
var newArr=[],obj={};
for(var i=0,len=this.length;i<len;i++){
if(!obj[typeof(this[i]) + this[i]]){
newArr.push(this[i]);
obj[typeof(this[i])+this[i]]='new';
}
}
return newArr;
};
alert(array.distinct());
function districtArray(array){
var result = new Array();
for(var i in array){
if(result.indexOf(array[i]) == -1){
result.push(array[i]);
}
}
return result;
};