js數組去重的hash方法


對於 JavaScript 數組去除重復項,現在有多種方法,其中一種是hash,如下:

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}就沒法區分了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM