在 JavaScript 中构造字符串时省略假值

javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/25 1:48:17

我们有一个包含一些字符串值和一些假值的数组。

我们需要编写一个 JavaScript 函数,该函数接受此数组并返回一个由连接数组的值并省略假值构成的字符串。

示例

其代码为 −

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

相关文章


有用资源