亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 JavaScript 中獲取數組中的對象?

如何在 JavaScript 中獲取數組中的對象?

慕沐林林 2022-11-27 16:12:15
我有一個 for 循環,我想利用我正在循環的數組中的一個對象。具體來說,我想利用我的對象的“名稱”部分來僅 console.log 名稱,而不是整個數組。這是代碼......我正在用貓鼬做這個,但我認為它與我的問題沒有任何關系,我只是想添加它。    const newCustomerNum2 = new customerList({    name: "John",    age: 32    });customerList.find(function(err, customers) {if (err) { console.log(err);} else {for (var i = 0; i<customers.length; i++){     console.log(customers.name);  }}});
查看完整描述

1 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

在你的for循環中發生的事情是,你正在遍歷你的數組的索引。假設您的數組有 3 個元素,for將使用i = 0, then i = 1, then調用循環i = 2。


該索引可用于引用數組中的對象。


當您調用時,customers.name您正在嘗試訪問name數組上的屬性而不是其中的數據。如果要訪問數組中的對象,請使用下標表達式:


customers[i]在哪里0 < i < customers.length。


這樣,您就可以console.log(customers[i].name)在循環中使用。


此外,您可以簡單地使用for ... of表達式,它遍歷數組的元素:


for (let customer of customers) {

    console.log(customer.name);

}


查看完整回答
反對 回復 2022-11-27
  • 1 回答
  • 0 關注
  • 405 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號