无法访问对象内的键

时间:2019-05-20 13:20:02

标签: javascript object

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

this.colleciton.find(x => x.details != null && x.details.numb != null && x.details.numb.toUpperCase && x.details.numb.toUpperCase() === numb)

当我<View style={{ position:"relative", top: calculateOffset(this.state.roll,this.state.screenOffset)+"%", width: "80%", height: "80%", backgroundColor: "transparent", justifyContent: "center", transform:[{rotate:`${this.state.pitch}deg`}]}} }} > <View style={{ height: 4, backgroundColor: "orange", width: "100%" }} /> </View> 时,它显示了整个对象。但是,当我尝试

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

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

console.log(options)

但是它只是返回

  

“ JSON中位置1处的意外令牌o”

5 个答案:

答案 0 :(得分:-1)

对象密钥名称中的.导致了此问题。当您这样做时:

  

options.account返回未定义

^这是因为没有名称为account的密钥

  

我在控制台登录“ options.account.country”时出错

^这是因为它试图在未定义的(options.account)上查找密钥country

您可以使用以下数组索引语法来解决此问题:

options['account.country']

options['account.phone']

答案 1 :(得分:-2)

要从字符串访问属性时,应使用括号表示法。

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

答案 2 :(得分:-2)

  

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

因为它是一个对象

  

当我console.log options.account时,它返回未定义

因为没有account属性。

account.countryaccount.phone。因此,您必须使用那些显式名称访问属性,例如:

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

但是它只是返回“位置1的JSON中的意外令牌o”

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

答案 3 :(得分:-2)

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

您可以使用options['account.country']

访问所需的值

答案 4 :(得分:-2)

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