从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' ]