访问嵌套在Javascript中另一个对象内的对象的属性

bro*_*web 2 javascript json object

我正在尝试访问嵌套在对象中的对象的属性.我是以错误的方式接近它,我的语法是错误的,还是两者兼而有之?我有更多的'联系人对象里面,但消除它们缩小这篇文章.

var friends = {
    steve:{
        firstName: "Rob",
        lastName: "Petterson",
        number: "100",
        address: ['Thor Drive','Mere','NY','11230']
    }
};

//test notation this works:
//alert(friends.steve.firstName);

function search(name){
    for (var x in friends){
        if(x === name){
               /*alert the firstName of the Person Object inside the friends object
               I thought this alert(friends.x.firstName);
               how do I access an object inside of an object?*/
        }
    }
}  

search('steve');
Run Code Online (Sandbox Code Playgroud)

Ved*_*ego 5

它是

friends.steve.firstName
Run Code Online (Sandbox Code Playgroud)

要么

friends["steve"].firstName
Run Code Online (Sandbox Code Playgroud)

但是,您不需要for循环:

function search(name){
    if (friends[name]) alert(friends[name].firstName);
}
Run Code Online (Sandbox Code Playgroud)

  • @brooklynsweb - 点符号只能用于编写代码时已知的常量字符串.它不能与存储在变量中的字符串一起使用.对于存储在变量或参数中的名称,使用`obj [varname]符号. (2认同)