เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและสลับคำที่อยู่ติดกันของสตริงนั้นกับอีกคำหนึ่งจนถึงจุดสิ้นสุดของสตริงนั้น
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const str = "This is a sample string only";
const replaceWords = str => {
return str.split(" ").reduce((acc, val, ind, arr) => {
if(ind % 2 === 1){
return acc;
}
acc += ((arr[ind+1] || "") + " " + val + " ");
return acc;
}, "");
};
console.log(replaceWords(str)); ผลลัพธ์
เอาต์พุตในคอนโซล −
is This sample a only string