javascript数组去重(undefined,null,NaN)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)的主要内容,如果未能解决你的问题,请参考以下文章