在javascript中从数组中过滤null [英] Filter null from an array in javascript

查看:446
本文介绍了在javascript中从数组中过滤null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项任务是从给定数组中删除false,null,0,,undefined和NaN元素。我致力于解决除了null之外的所有解决方案。有谁能解释为什么?这是代码:

I have a task to remove false, null, 0, "", undefined, and NaN elements from an given array. I worked on a solution wich removes all except 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]

编辑:显然演员不是'需要:

Apparently the cast isn't needed:

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

上面的代码删除 null 就好了,这是 NaN 这就是问题所在。 Nina在她的回答中说, NaN!== NaN

And the code above removes null just fine, it's NaN that's the problem. NaN !== NaN as Nina says in her answer.

这篇关于在javascript中从数组中过滤null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆