เรามีอาร์เรย์ที่มีค่าว่างอยู่ภายในแบบนี้:
const arr = [43, 534534, 645, 64, , 645, 64, , 645, , 645, , 65, , 645, , 64];
เราต้องเขียนฟังก์ชันอาร์เรย์ pushAtEmpty() ที่รับองค์ประกอบหนึ่งและใส่มันที่ดัชนีว่างแรกที่เจอในอาร์เรย์ที่ใช้ในบริบท ถ้าไม่มีที่ว่าง องค์ประกอบควรถูก push ไปท้ายอาร์เรย์
มาเขียนโค้ดสำหรับฟังก์ชันนี้ เราจะค้นหาดัชนีของตำแหน่งว่างก่อน แล้วแทนที่ค่าที่นั่นด้วยค่าที่เราได้รับ
ตัวอย่างโค้ด
const arr = [43, 534534, 645, 64, , 645, 64, , 645, , 645, , 65, , 645, , 64];
Array.prototype.pushAtEmpty = function(element) {
let index;
for (index = 0; index < this.length; index++) {
if (arr[index] === undefined) {
this.splice(index, 1, element);
break;
}
}
if (index === this.length) {
this.push(element);
}
};
arr.pushAtEmpty(23);
arr.pushAtEmpty(33);
arr.pushAtEmpty(43);
arr.pushAtEmpty(53);
arr.pushAtEmpty(63);
arr.pushAtEmpty(73);
arr.pushAtEmpty(83);
arr.pushAtEmpty(93);
console.log(arr);
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
[ 43, 534534, 645, 64, 23, 645, 64, 33, 645, 43, 645, 53, 65, 63, 645, 73, 64, 83, 93 ]