[英]accessing properties of nested objects
我是Java的新手,目前正在codecademy.com上學習
這是我不了解的部分:
var friends = {};
friends.bill={};
friends.steve={};
friends.bill={
firstName:"Bill",
lastName:"Will",
number:4164567889,
address: ['298 Timberbank blvd', 'scarborough', 'ontario']
};
friends.steve={
firstName:"Steve",
lastName:"Evan",
number:4161233333,
address: ['111 Timberbank blvd', 'scarborough', 'ontario']
for ( var keys in friends){
console.log(keys); // 1. returns 2 objects of friends(bill, steve)
console.log(keys.firstName); // 2. why is this wrong?
console.log(friends[keys].firstName); // 3. why the properties has to be accessed in this way?
}
到目前為止,我只能假設“ for..in”循環返回“ friends”中對象的數組。 這就是為什么必須使用[]表示法對其進行訪問的原因。 如果我錯了,請糾正我。 謝謝
for...in
循環遍歷對象的鍵 。
因此, keys
是字符串“ bill”或“ steve”,而不是您的朋友對象。 因此keys.firstName
計算結果為"bill".firstName
和"steve".firstName
,這當然是毫無意義的。
要在您的friends對象中獲取鍵“ bill”的對象,可以使用friends.bill
,也可以使用friends['bill']
。 Bot表達式是相等的,但是后者允許您使用變量而不是編譯時已知的字符串。 因此,您可以使用keys
來代替'bill'
例如: friends[keys]
。 然后,這實際上將是您在朋友中的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.