js數組去重的hash方法

對於 JavaScript 數組去除重複項,如今有多種方法,其中一種是hash,以下:html

if (!Array.prototype.unique) {
  Array.prototype.unique = function () {
    var hash = {}, result = [], item;
    for (var i = 0; i < this.length; i++) {
      item = this[i];
      if ( !hash[item] ) {
        hash[item] = true;
        result.push(item);
      }
    }
    return result;
  };
}

可是該方法並不嚴謹,沒法區分數字 1 和 字符串 '1'數組

var arr = [0, 1, '1', true, 5, true, false, undefined, undefined, null, null];
arr.unique();

 

修改一下,加上數據類型判斷:函數

if (!Array.prototype.unique) {
  Array.prototype.unique = function () {
    var hash = {}, result = [], type = '', item;
    for (var i = 0; i < this.length; i++) {
      item = this[i];
      type = Object.prototype.toString.call(item);

      if ( !hash[item + type] ) {
        hash[item + type] = true;
        result.push(item);
      }
    }
    return result;
  };
}

至少如今對5種原始數據類型的值能夠準確去重了,對某些引用類型的值──數組,函數,也能夠,可是對象類型──{"name": 1}, {"name": 2}就無法區分了。this

相關文章
相關標籤/搜索