javascript - 为什么 JSON.parse() 不解析 JSON 对象的内部数组?
问题描述
有谁知道为什么我的 JSON.parse() 不能正常工作?我已经尝试了所有的调试工具,但它没有解析数组。
我的代码:
console.log(typeof(localStorage.array));
console.log(localStorage.array);
localStorageArray = JSON.parse(localStorage.array);
console.log(localStorageArray);
控制台:
String //line 1
[[{"color":"#000000","teacher":"ELA","tasks":[[{"selection":"homework","name":"HW 1","date":"2020-05-15","time":"16:05","marked":false}]]}]] //line 2
Array(1)
0: Array(1)
0:
color: "#000000"
tasks: Array(0)
length: 0
__proto__: Array(0)
teacher: "ELA"
__proto__: Object
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0) //The main thing here is that tasks.length == 0
解决方案
该localStorage
对象具有与普通 JavaScript 属性不同的自定义属性 getter/setter object
。
这在这里解释(强调我的):
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
键和值始终是字符串(请注意,与对象一样,整数键将自动转换为字符串)。
因此,当您从属性中检索值时localStorage
,它将始终作为 a 返回string
,即使您只是为属性设置了object
值。
您应该更喜欢getItem
andsetItem
函数来避免这种自动字符串转换。
推荐阅读
- json - 如何修复 XML HTTP 请求中的“下标超出范围”错误
- android - 如何将一个android活动连接到另一个?
- c++ - 单个作者 + 阅读器的发布/检查更新类是否可以使用 memory_order_relaxed 或获取/释放以提高效率?
- api - 如何按字母顺序对 Github 用户 API 进行排序
- java - 为什么@PostConstruct 方法中实际上只能启动一个线程?
- c# - Aspnet Core Identity 登录和注册谷歌浏览器不起作用
- azure-logic-apps - 为什么 gmail 连接器触发器会跳过新的传入电子邮件
- python - 为什么我的代码打印出我尚未分配的值?
- java - 供应商
> 不能多次迭代 - git - 有没有办法让 GitHub CI 构建 PR 的测试合并,而不是 PR 分支的负责人?