【问题标题】:Cannot access keys inside Object [duplicate]无法访问对象内的键[重复]
【发布时间】:2019-10-06 21:03:07
【问题描述】:

我正在尝试访问 Javascript 对象中键的值。我的对象目前看起来像:

const options = {
  "account.country": getCountry,
  "account.phone": getPhone,
}

当我console.log(options) 时,它显示整个对象。但是,当我尝试时

console.log(options.account) // undefined, 
console.log(options.account.country) // error. 

我不明白为什么。我也试过了:

 const parsedObj = JSON.parse(options);
 console.log(parsedObj);

但它只是返回

'JSON 中位置 1 的意外标记 o'

【问题讨论】:

标签: javascript object


【解决方案1】:

当您想从字符串访问属性时,您应该使用括号表示法。

const options = {
  "account.country": 'getCountry',
  "account.phone": 'getPhone',
}
console.log(options['account.country'])

【讨论】:

    【解决方案2】:

    当我 console.log 'options' 时,它会显示整个对象

    因为它是一个对象

    当我 console.log options.account 它返回 undefined

    因为没有account 属性。

    仅限 account.countryaccount.phone。因此,您必须使用这些显式名称访问属性,如下所示:

    console.log(options['account.country']);
    

    但它只是返回“位置 1 处 JSON 中的意外标记 o”

    它是一个对象,而不是 JSON 字符串。

    【讨论】:

    • 这个答案对帮助用户理解他显然没有的概念没有任何帮助。
    • @Jhawins — 它清楚地解释了现有尝试失败的原因,并演示了解决问题所需的修改。
    【解决方案3】:
    const options = {
      "account.country": 'getCountry',
      "account.phone": 'getPhone',
    }
    

    您可以使用options['account.country'] 访问所需的值

    【讨论】:

      【解决方案4】:

      let options = {
        "account.country": "getCountry",
        "account.phone": "getPhone"
      }
      console.log(options["account.country"])

      【讨论】:

      • 展示如何构建合适的对象会更有帮助(因为那是 OP 的意图)
      【解决方案5】:

      对象键名中的. 导致了此问题。当你这样做时:

      options.account 它返回 undefined

      ^ 那是因为没有名称为account的键

      当我在控制台记录“options.account.country”时出现错误

      ^ 那是因为它试图在 undefined (options.account) 上查找密钥 country

      您可以通过使用数组索引语法来解决这个问题,如下所示:

      options['account.country']
      
      options['account.phone']
      

      【讨论】:

        猜你喜欢
        • 2012-10-09
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        • 2012-10-15
        • 2019-04-03
        • 1970-01-01
        相关资源
        最近更新 更多