在 JavaScript 中过滤数组中的 null?
javascriptweb developmentobject oriented programming更新于 2025/11/16 4:28:17
要从数组中过滤 null 并仅显示非 null 值,请使用 filter()。以下是代码 −
示例
var
names=[null,"John",null,"David","","Mike",null,undefined,"Bob","Adam",null,null];
console.log("Before filter null=");
console.log(names);
var filterNull=[];
filterNullValues=names.filter(obj=>obj);
console.log("After filtering the null values=");
console.log(filterNullValues);
要运行上述程序,您需要使用以下命令 −
node fileName.js.
输出
此处,我的文件名为 demo148.js。这将产生以下输出 −
PS C:\Users\Amit\JavaScript-code> node demo148.js Before filter null=[ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 'Adam', null, null ] After filtering the null values= [ 'John', 'David', 'Mike', 'Bob', 'Adam' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

