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

更新於: 14-Sep-2020

394 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始學習
廣告