เพิ่มเมธอด pushAtFalsy() ให้ Array.prototype: แทรกสมาชิกที่ index แรกที่เป็น falsy (ยกเว้น 0)
ตัวอย่าง
Input: [13, 34, 65, null, 64, false, 65, 14, undefined, 0, , 5, , 6, ,85, ,334] Insert: 4, 42, 424, 4242, 42424, 424242, 4242424 Output: แทรกที่ null, false, undefined, empty slot, empty slot, empty slot, empty slot
ตัวอย่างโค้ด
const arr = [13, 34, 65, null, 64, false, 65, 14, undefined, 0, , 5, , 6, ,85, ,334];
const pushAtFalsy = function(element) {
let index;
for (index = 0; index < this.length; index++) {
// falsy แต่ไม่ใช่ตัวเลข (0 เป็น falsy แต่เป็นตัวเลข)
if (!this[index] && typeof this[index] !== 'number') {
this.splice(index, 1, element);
break;
}
}
if (index === this.length) this.push(element);
};
Array.prototype.pushAtFalsy = pushAtFalsy;
arr.pushAtFalsy(4);
arr.pushAtFalsy(42);
arr.pushAtFalsy(424);
arr.pushAtFalsy(4242);
arr.pushAtFalsy(42424);
arr.pushAtFalsy(424242);
arr.pushAtFalsy(4242424);
console.log(arr);
ข้อควรระวัง
- การแก้ไข
Array.prototypeเป็น anti-pattern - Sparse arrays (ช่องว่าง
,,) มีค่าundefinedที่ index นั้น 0เป็น falsy แต่โค้ดข้ามไปด้วยtypeof !== 'number'
ผลลัพธ์
[ 13, 34, 65, 4, 64, 42, 65, 14, 424, 0, 4242, 5, 42424, 6, 424242, 85, 4242424, 334 ]