从数组中删除所有虚假值 [英] Remove all falsy values from an array

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

问题描述

我想从数组中删除所有虚假值.JavaScript 中的假值是 false、null、0、""、undefined 和 NaN.

I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

function bouncer(arr) {
 arr = arr.filter(function (n) { 
    return (n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && isNaN()!=NaN); });
  return arr;
}

bouncer([7, "ate", "", false, 9, NaN], "");

除 NaN 测试用例外,以上所有内容都得到满足.有人可以帮我检查数组是否包含 NaN 吗?

The above is getting satisfied for all except the NaN test case. Can someone help me check in the array whether it contains NaN or not?

推荐答案

你可以使用 Boolean :

You can use Boolean :

var myFilterArray = myArray.filter(Boolean);

这篇关于从数组中删除所有虚假值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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