简体   繁体   English

在 JavaScript 中从数组中过滤 null

[英]Filter null from an array in JavaScript

I have a task to remove false, null, 0, "", undefined, and NaN elements from an given array.我的任务是从给定数组中删除 false、null、0、""、undefined 和 NaN 元素。 I worked on a solution which removes all except null.我研究了一个解决方案,它删除了除 null 之外的所有内容。 Anyone can explain why?任何人都可以解释为什么? Here's the code:这是代码:

function bouncer(arr) {
var notAllowed = ["",false,null,0,undefined,NaN];
  for (i = 0; i < arr.length; i++){
      for (j=0; j<notAllowed.length;j++) {
         arr = arr.filter(function(val) {
               return val !== notAllowed[j];
              });
  }
 }
return arr;
}

bouncer([1,"", null, NaN, 2, undefined,4,5,6]);

Well, since all of your values are falsy, just do a !!好吧,既然你所有的值都是假的,就做一个!! (cast to boolean) check: (转换为布尔值)检查:

[1,"", null, NaN, 2, undefined,4,5,6].filter(x => !!x); //returns [1, 2, 4, 5, 6]

Edit: Apparently the cast isn't needed:编辑:显然不需要演员表:

 document.write([1,"", null, NaN, 2, undefined,4,5,6].filter(x => x));

And the code above removes "" , null , undefined and NaN just fine.上面的代码删除了""nullundefinedNaN就好了。

It is a problem with NaN , because这是NaN的问题,因为

NaN !== NaN

read more here: Testing against NaN .在此处阅读更多信息: 针对NaN测试

For filtering the values, you could check for truthyness.为了过滤值,您可以检查真实性。

 function bouncer(arr) { return arr.filter(Boolean); } console.log(bouncer([1, "", null, NaN, 2, undefined, 4, 5, 6]));

You can use Array.prototype.filter for truthy value check - see demo below:您可以使用Array.prototype.filter进行值检查 - 请参见下面的演示:

 function bouncer(array) { return array.filter(function(e) { return e; }); } console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

Use

 function bouncer(arr) { return arr.filter(function(item){ return !!item; }); } console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

[1, 2, 0, null, "sdf", ""].filter(a=>a)
// filter non null value, remove 0, null and "" (empty quote)

 console.log([1, 2, 0, null, "sdf", ""].filter(a=>a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM