码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-05 11:48:29      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:数据   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)

标签:数据   nan   json   对象   round   prot   define   []   property   

原文地址:http://www.cnblogs.com/xunling/p/7119811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!