首页 > 代码库 > javascript数组去重(undefined,null,NaN)

javascript数组去重(undefined,null,NaN)

  数组去重记录:

  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)