简体   繁体   English

访问嵌套对象的属性

[英]accessing properties of nested objects

I'm new to Javascript, and currently learning it on codecademy.com 我是Java的新手,目前正在codecademy.com上学习

Here's the part I don't understand: 这是我不了解的部分:

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?
}

so far the only thing I can assume is the "for..in" loop returns an array of the objects in "friends". 到目前为止,我只能假设“ for..in”循环返回“ friends”中对象的数组。 that's why it has to be accessed by using [] notation. 这就是为什么必须使用[]表示法对其进行访问的原因。 Correct me if I was wrong. 如果我错了,请纠正我。 Thank you 谢谢

The for...in loop iterates over the keys of an Object. for...in循环遍历对象的

So keys is either the string "bill" or "steve", not your friends objects. 因此, keys是字符串“ bill”或“ steve”,而不是您的朋友对象。 So keys.firstName evaluates to "bill".firstName and "steve".firstName , which of course is meaningless. 因此keys.firstName计算结果为"bill".firstName"steve".firstName ,这当然是毫无意义的。

To get the object for the key "bill" in your friends object you can use either friends.bill or you can use friends['bill'] . 要在您的friends对象中获取键“ bill”的对象,可以使用friends.bill ,也可以使用friends['bill'] Bot expressions are equal, but the later allows you to use a variable instead of a string known at compile time. Bot表达式是相等的,但是后者允许您使用变量而不是编译时已知的字符串。 Thus you can use keys instead of 'bill' like this: friends[keys] . 因此,您可以使用keys来代替'bill'例如: friends[keys] Then this will actually be your object in friends. 然后,这实际上将是您在朋友中的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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