從 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