【问题标题】:Can't access object properties even though I can see they exist即使我可以看到它们存在也无法访问对象属性
【发布时间】:2019-08-15 21:52:27
【问题描述】:

我无法访问任何对象属性,一直未定义。

我试过了

console.log(JSON.parse(this.$store.state.user.userId));

console.log(JSON.parse(this.$store.state.user[0].userId));

当我这样做时

console.log(JSON.parse(this.$store.state.user.userId));

我明白了

"SyntaxError: Unexpected token u in JSON at position 0"

当我这样做的时候

 console.log(JSON.parse(this.$store.state.user));

我得到了对象,我可以看到属性。只是每当我尝试访问它们时,我都会得到undefined

【问题讨论】:

  • 您也必须发布对象的内容。但我的猜测是一个错字

标签: javascript vue.js


【解决方案1】:

当我只是做 console.log(JSON.parse(this.$store.state.user));我得到了对象,我可以看到属性。

这意味着this.$store.state.user 包含描述user 对象的JSON 字符串。

因此JSON.parse(this.$store.state.user.userId) 不正确。在这种情况下,您试图从字符串中获取属性userId,在第一个符号'u' 上获取undefinedJSON.parse 函数失败。

您应该改用JSON.parse(this.$store.state.user).userId

【讨论】:

  • 不客气。我很感激,如果你标记我的答案,只要它有帮助
猜你喜欢
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2021-02-05
  • 2022-11-10
  • 1970-01-01
相关资源
最近更新 更多