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

วนลูป for ในอ็อบเจ็กต์เพื่อดึงข้อมูล CustomerId คี่ใน JavaScript

ใช้ลูป for ตรวจสอบ customerId % 2 != 0

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

var customerDetails = [
    { customerId: 101, customerName: "John" },
    { customerId: 102, customerName: "David" },
    { customerId: 103, customerName: "Mike" },
    { customerId: 104, customerName: "Bob" }
];

for (var index = 0; index < customerDetails.length; index++) {
    if (customerDetails[index].customerId % 2 != 0) {
        console.log("Customer Id=" + customerDetails[index].customerId);
        console.log("Customer Name=" + customerDetails[index].customerName);
        console.log("-----------------------------------------------------------");
    }
}

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

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

ผลลัพธ์

Customer Id=101
Customer Name=John
-----------------------------------------------------------
Customer Id=103
Customer Name=Mike
-----------------------------------------------------------