含对象的数组经JSON.stringify存入localStorage后解析报错,如何解决?
解决localStorage解析数组时的JSON语法错误
你的问题出在localStorage.getItem的用法上——这个方法只需要传入存储的键名作为参数,你错误地把JSON.parse当成第二个参数传进去了,导致JSON.parse接收的不是存储的JSON字符串,而是无效内容,才抛出了语法错误。
完全可以解析这类数组,修复方法很简单,分两步正确取出并解析:
- 先通过
getItem获取存储的JSON字符串 - 再用
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
相关产品推荐
相关产品推荐

