JavaScript - 將帶有 null 值的陣列轉換為字串
我們有一個包含一些字串值以及一些空值陣列。
我們需要編寫一個 JavaScript 函式,該函式接受此陣列並返回一個透過連線陣列值並省略空值而構建的字串。
以下是我們具有某些空和未定義值的陣列 −
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];
讓我們編寫此函式的程式碼 −
示例
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of",
"a", null, "sentence"];
const joinArray = arr => {
const sentence = arr.reduce((acc, val) => {
return acc + (val || "");
}, "");
return sentence;
};
console.log(joinArray(arr));輸出
以下是在控制檯中的輸出 −
Hereisanexampleofasentence
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP