javascript - Can't access object properties even though I can see they exist
问题描述
I can't access any of the object properties, keep getting undefined.
I have tried
console.log(JSON.parse(this.$store.state.user.userId));
and
console.log(JSON.parse(this.$store.state.user[0].userId));
When I do
console.log(JSON.parse(this.$store.state.user.userId));
I get
"SyntaxError: Unexpected token u in JSON at position 0"
When I just do
console.log(JSON.parse(this.$store.state.user));
I get the object and I can see the properties. It's just that whenever I try to access them I get undefined
.
解决方案
When I just do console.log(JSON.parse(this.$store.state.user)); I get the object and I can see the properties.
This means that this.$store.state.user
contains JSON string which describes the user
object.
Thus JSON.parse(this.$store.state.user.userId)
is incorrect. In this case you are trying to get property userId
from string, getting undefined
and JSON.parse
function fails on the first symbol, which is 'u'
.
You should use JSON.parse(this.$store.state.user).userId
instead.
推荐阅读
- javascript - 使用 JavaScript 检测用户安装的浏览器扩展
- sympy - sympy:我想校准 3-PLane-Intersection
- php - 按每行中第一个子数组的文本对数组进行排序
- c++ - 为什么这个指针是 8 个字节?
- sql - 新列中的 Sql 实例号
- javascript - 如何替换未察觉的 div 元素
- java - 提高在 ArrayList 中查找和使用重复元素的效率
- python - 运行 stokesCavity.py 示例时出现查看器错误
- web-scraping - 网络抓取 Obsidian 已发布的保险库
- python - 我在 reducer 输出中得到一个列表列表,而不是成对的值,我不确定在我的代码中要更改什么