首页 > 代码库 > 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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。