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

JavaScript数据去掉空值

时间:2017-10-30 18:26:03      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:markdown   note   net   print   keyword   isnan   iter   fun   key   

js数组中过滤掉false, null, 0, "", undefined, and NaN值的方法

对于 false,null,0,undefiend,NaN直接取!得到的都是true,因此这里只需要在判断空字符串""; 
直接看代码:


function bouncer(arr) {
  // Don‘t show a false ID to this bouncer.
  return arr.filter(function(val){
    return !(!val || val === "");
  });
}

bouncer([7, "ate", "", false, 9]);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行结果:

bouncer([7, “ate”, “”, false, 9]);

当入参是[false, null, 0, NaN, undefined, ""] 
运行结果是

[]

这里要注意:NaN与任何值比较包括它自身结果都是false,因此可以使用isNaN()函数来检查;

 

 

Array.prototype.notempty = function(){

    return this.filter(t => t!=undefined && t!==null);
}

JavaScript数据去掉空值

标签:markdown   note   net   print   keyword   isnan   iter   fun   key   

原文地址:http://www.cnblogs.com/gotodsp/p/7755361.html

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