【问题标题】:Accessing a property of an object that is nested inside another object in Javascript访问嵌套在 Javascript 中的另一个对象内的对象的属性
【发布时间】: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');

【问题讨论】:

标签: javascript json object


【解决方案1】:

要么是

friends.steve.firstName

friends["steve"].firstName

不过,您不需要 for 循环:

function search(name){
    if (friends[name]) alert(friends[name].firstName);
}

【讨论】:

  • 类似主题的问题;为什么我不能使用点符号? //this works function search(name){ if(friends[name]){ alert(friends[name].firstName); } //this does not function search(name){ if(friends.name){ alert(friends.name.firstName); } }
  • @brooklynsweb - 点符号只能用于编写代码时已知的常量字符串。它不能与存储在变量中的字符串一起使用。对于存储在变量或参数中的名称,请使用 obj[varname] 表示法。
  • @brooklynsweb 详细说明 jfriend00 写了什么……如果你写 friends.name,JavaScript 怎么知道你的意思是“称为(字面意思)name 的字段”还是“字段命名为变量name中的任何内容”?括号表示法允许您指定:friend[name] 是一个“以变量name 中的任何内容命名的字段”,而friend["name"] 是一个“称为(字面意思)name 的字段”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
相关资源
最近更新 更多