You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含对象的数组经JSON.stringify存入localStorage后解析报错,如何解决?

解决localStorage解析数组时的JSON语法错误

你的问题出在localStorage.getItem的用法上——这个方法只需要传入存储的键名作为参数,你错误地把JSON.parse当成第二个参数传进去了,导致JSON.parse接收的不是存储的JSON字符串,而是无效内容,才抛出了语法错误。

完全可以解析这类数组,修复方法很简单,分两步正确取出并解析:

  1. 先通过getItem获取存储的JSON字符串
  2. 再用JSON.parse把字符串转换成JS数组

正确代码示例:

// 取出存储的JSON字符串
const storedPoints = localStorage.getItem('allPoints');
// 解析为JS数组
const allPoints = JSON.parse(storedPoints);

额外提醒:如果localStorage里没有allPoints这个键,getItem会返回null,直接解析会报错,建议加个兜底判断:

const storedPoints = localStorage.getItem('allPoints');
// 如果没有存储数据,就用初始数组兜底
const allPoints = storedPoints ? JSON.parse(storedPoints) : [{ gained: 0, lost: 0 }];

内容的提问来源于stack exchange,提问作者W4IT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:50:26