我正在尝试访问嵌套在对象中的对象的属性。我是以错误的方式接近它,我的语法是错误的,还是两者兼而有之?我内部有更多'联系人对象,但是删除它们以缩小这个帖子。
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');
答案 0 :(得分:5)
要么是
friends.steve.firstName
或
friends["steve"].firstName
但是你不需要for循环:
function search(name){
if (friends[name]) alert(friends[name].firstName);
}