สมมติว่าเรามีอาร์เรย์ของค่าคงที่ดังนี้:
const arr = [4, 6, , 45, 3, 345, , 56, 6];
เราต้องเขียนฟังก์ชันที่รับอาร์เรย์แบบนี้และลบสมาชิก undefined ทั้งหมดออกจากอาร์เรย์ในที่เดิม (in place) เราต้องลบเฉพาะ undefined และค่าว่าง ไม่ใช่ค่า falsy ทั้งหมด
ใช้ลูป for วนผ่านอาร์เรย์ และ Array.prototype.splice() เพื่อลบ undefined ในที่เดิม
ตัวอย่าง
โค้ดต่อไปนี้เป็นตัวอย่าง:
const arr = [4, 6, , 45, 3, 345, , 56, 6]
const eliminateUndefined = arr => {
for(let i = 0; i < arr.length; ){
if(typeof arr[i] !== 'undefined'){
i++;
continue;
};
arr.splice(i, 1);
};
};
eliminateUndefined(arr);
console.log(arr);ผลลัพธ์
จะแสดงผลในคอนโซลดังนี้:
[ 4, 6, 45, 3, 345, 56, 6 ]