Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript - แปลง Array ที่มี Null Values เป็น String

โจทย์

รวม array elements เป็น string โดยข้าม null/undefined values

Input: ["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

คำอธิบาย

reduce สะสม string
val || "" ใช้ short-circuit evaluation: null, undefined, 0, "" → falsy → ใช้ "" แทน
ค่า truthy ("Here", "is", "an", "example", "of", "a", "sentence") ถูกต่อกัน
หมายเหตุ: 0 และ "" ก็ถูกข้ามด้วย เพราะเป็น falsy