从 JavaScript 中的数组中过滤掉 null?


如需从数组中过滤掉 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' ]

更新日期: 11-Sep-2020

985 个浏览量

开启你的 职业

通过完成课程取得资格认证

开始
广告
© . All rights reserved.