从 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' ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP