array中去重

方法1:

function unique(arr){

  var newArray=[];

  var hashTable={};

  for (var i = 0, item; (item=this[i]) != null; i++){

    if(!hashTable[item]){
      newArray.push(item);
      hashTable[item] = true;
    }
  }

  return newArray;

}

 

方法2:

function unique(array){

  return arr.filter(function(elem, pos, self) {

    return self.indexof(elem, pos+1) === -1;
  });

}

filter方法第一个参数为数组中的当前值,第二个是它的index,第三个是数组本身。

使用indexof方法从pos+1的位置找elem,如果没找到说明是unique的,找到了就返回false,剔除当前元素。

 

posted @ 2016-02-10 22:36  小白兔纸白又白  阅读(153)  评论(0编辑  收藏  举报