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 に答える