เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ที่มีค่าเท็จบางอย่าง ฟังก์ชันควรลบค่า Null ทั้งหมดออกจากอาร์เรย์ (ถ้ามี) อยู่ในตำแหน่ง
ตัวอย่างเช่น หากอาร์เรย์อินพุตเป็น −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null];
จากนั้นผลลัพธ์ควรเป็น −
const output = [12, 5, undefined, 0, false, 67, undefined, false];
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined,
false, null];
const removeNullValues = arr => {
for(let i = 0; i < arr.length; ){
// null's datatype is object and it is a false value
// so only falsy object that exists in JavaScript is null
if(typeof arr[i] === 'object' && !arr[i]){
arr.splice(i, 1);
}else{
i++;
continue;
};
};
};
removeNullValues(arr);
console.log(arr); ผลลัพธ์
เอาต์พุตในคอนโซล −
[ 12, 5, undefined, 0, false, 67, undefined, false ]