Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ลบค่า 0, undefined และค่าว่างออกจากอาเรย์ใน JavaScript

ใช้ลูป for ร่วมกับ splice() ลบค่า Falsy (0, false, '', null, undefined)

ตัวอย่างโค้ด

var allValues = [10, false, 100, 150, '', undefined, 450, null];

console.log("Actual Array=");
console.log(allValues);

for (var index = 0; index < allValues.length; index++) {
    if (!allValues[index]) {
        allValues.splice(index, 1);
        index--;
    }
}

console.log("After removing false, undefined, null or ''...=");
console.log(allValues);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo88.js)

ผลลัพธ์

Actual Array= [ 10, false, 100, 150, '', undefined, 450, null ]
After removing false, undefined, null or ''...= [ 10, 100, 150, 450 ]