3

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

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');
4

1 回答 1

6

它是

friends.steve.firstName

或者

friends["steve"].firstName

但是,您不需要 for 循环:

function search(name){
    if (friends[name]) alert(friends[name].firstName);
}
于 2013-10-01T00:08:47.937 回答