เรามีอาร์เรย์ที่มีค่าสตริงและค่าว่างบางส่วน
เราจำเป็นต้องเขียนฟังก์ชัน 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