【发布时间】:2013-10-01 00:04:51
【问题描述】:
我正在尝试访问嵌套在对象内的对象的属性。我是以错误的方式接近它,是我的语法错误,还是两者兼而有之?我里面有更多的“联系人”对象,但为了缩小这篇文章,我删除了它们。
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。 -
这很有道理,谢谢!
标签: javascript json object