สมมติว่าต่อไปนี้เป็นวัตถุของเรา −
var customerDetails=
[
{
customerId:101,
customerName:"John"
},
{
customerId:102,
customerName:"David"
},
{
customerId:103,
customerName:"Mike"
},
{
customerId:104,
customerName:"Bob"
}
] ใช้สำหรับวนซ้ำโดยมีเงื่อนไขต่อไปนี้เพื่อแสดงเฉพาะบันทึก CustomerID คี่ -
for(var index=0;index<customerDetails.length;index++){
if(customerDetails[index].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("---------------------------------------------------
--------")
}
console.log("");
} ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo71.js
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
PS C:\Users\Amit\JavaScript-code> node demo71.js Customer Id=101 Customer Name=John ----------------------------------------------------------- Customer Id=103 Customer Name=Mike -----------------------------------------------------------