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)
它是
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)