laijbin / Blog

Note insights and personal development.
0 stars 0 forks source link

数组去重 #13

Open laijbin opened 8 years ago

laijbin commented 8 years ago

方法一:

function undulpicate(arr){  
      for(var i = 0;i<arr.length; i++){
        for(var j=i+1;j < arr.length;j++) {  
           if(arr[i]===arr[j]) {  
                arr.splice(j,1);  
                j--;  
            }  
        }  
    }  
    return arr;  
} 
var b = [1,2,3,1,2,3,'1','2','3',new String(1), new Number(1)];
undulpicate(b);

方法一问题:多重循环

方法二:

function undulpicate(arr) {
  var ret = []
  var hash = {}

  for (var i = 0; i < arr.length; i++) {
    var item = arr[i]
    var key = typeof(item) + item
    if (hash[key] !== 1) {
      ret.push(item)
      hash[key] = 1
    }
  }

  return ret
}

var a = [1,2,3,1,2,3,'1','2','3'];
undulpicate(a);

方法二问题:分不出var b = [new String(1), new Number(1)];