javascript數組去重(undefined,null,NaN)

來源:互聯網
上載者:User

標籤:資料   nan   json   對象   round   prot   define   []   property   

  數組去重記錄:

  1、indexOf 方法,無法識別NaN

 

1     var ary = [false, true, undefined, null, NaN, 0, 1, 1, "1", "1", {}, {}, "a", "a", NaN];2 3     Array.prototype.uniq = function() {4         var _this = this;5         return _this.filter(function(item, pos) {6             return _this.indexOf(item) == pos;7         })8     }

  2、hasOwnProperty,對象屬性檢測,無法識別 1,‘1’

1     var ary = [false, true, undefined, null, NaN, 0, 1, 1, "1", "1", {}, {}, "a", "a", NaN];2 3     Array.prototype.uniq = function() {4         var map = {};5         return this.filter(function(item) {6             return map.hasOwnProperty(item) ? false : (map[item] = true);7         });8     }

  3、type of 資料類型,無法區分{}

 1     var ary = [false, true, undefined, null, NaN, 0, 1, 1, "1", "1", {}, {}, "a", "a", NaN]; 2  3  4     Array.prototype.uniq = function() { 5         var prims = { 6             boolean: {}, 7             number: {}, 8             string: {} 9         };10         var obj = [];11         return this.filter(function(item) {12             var type = typeof item;13             if (type in prims) {14                 return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);15             } else {16                 return obj.indexOf(item) != -1 ? false : (obj.push(item));17             }18         })19     }

  4、資料類型+對象  //效果好,能夠準確區分

 1     var ary = [false, true, undefined, null, NaN, 0, 1, 1, "1", "1", {}, {}, "a", "a", NaN]; 2  3      Array.prototype.uniq = function () { 4          var map = {}; 5          return this.filter(function (item) { 6              var key = typeof item + item; 7              console.log(key) 8              return map.hasOwnProperty(key) ? false : (map[key] = true); 9          });10      };

  5、JSON.stringify  //無法區分NaN,null

1     var ary = [false, true, undefined, null, NaN, 0, 1, 1, "1", "1", {}, {}, "a", "a", NaN];2 3     Array.prototype.uniq = function() {4         var map = {};5         return this.filter(function(item) {6             var key = JSON.stringify(item);7             return map.hasOwnProperty(key) ? false : (map[key] = true);8         })9     }

  

 

javascript數組去重(undefined,null,NaN)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.