gpt4 book ai didi

javascript - 在 JavaScript 中从数组中过滤 null

转载 作者:行者123 更新时间:2023-12-03 01:07:08 25 4
gpt4 key购买 nike

我的任务是从给定数组中删除 false、null、0、""、undefined 和 NaN 元素。我研究了一个解决方案,删除除 null 之外的所有内容。任何人都可以解释为什么吗?代码如下:

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]);

最佳答案

好吧,由于您的所有值都是假的,因此只需执行 !! (转换为 bool 值)检查:

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

编辑:显然不需要 Actor 阵容:

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

上面的代码删除了 ""nullundefinedNaN 就好了。

关于javascript - 在 JavaScript 中从数组中过滤 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41346902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com