為在物件內使用 for 迴圈迭代以獲取具有奇數 CustomerId 的記錄 JavaScript 中 for 迴圈的迭代 ?


假設如下是我們的物件 -

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

與以下條件一起使用 for 迴圈,僅顯示奇數 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
-----------------------------------------------------------

更新於: 07-Sep-2020

208 檢視

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.