繁体   English   中英

访问嵌套对象的属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM