我试图访问嵌套在对象内部的对象的属性。我的方法是否不正确,我的语法是否有误,还是两者都有问题?我曾经拥有更多的“联系人对象”,但为了缩小这篇文章,我将它们删除了。
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');
x
是一个变量,你需要使用friends[x].firstName
。而friends.x.firstname
会寻找字面上的键值x
。 - Evan Davis