javascript - 未捕获的 SyntaxError:JSON 输入意外结束:在 JSON.parse()
问题描述
当我尝试解析 localStorage['highscores"] 时它会引发错误
if (localStorage["highscores"] == undefined) {
localStorage["highscores"] = [];
}
var highscores = JSON.parse(localStorage["highscores"]) || [];
我还没有定义 localStorage['highscores"] 所以我尝试检查它,如果它未定义,则定义它,如果它已满,我想将它的信息保存在 localStorage['highscores"] 中并添加更多信息。
有任何想法吗?
解决方案
本地存储只能保存字符串。当您为其设置非字符串时,它将被强制转换为字符串。
当数组转换为字符串时,.join(',')
在字符串上调用。空数组将转换为空字符串:
console.log(String([]) === '');
这不是 JSON 可解析的。
改为保存空数组的 JSON 字符串化版本。
if (localStorage.highscores === undefined) {
localStorage.highscores = '[]';
}
或者
if (localStorage.highscores === undefined) {
localStorage.highscores = JSON.stringify([]);
}
如有疑问,在与本地存储之间传输时始终使用JSON.stringify
/ 。JSON.parse
推荐阅读
- html - 在标签以外的元素上使用 for 属性
- c++ - 向 std::thread 对象发送参数
- java - Java字符串数组,计算空格数“”
- python - 使用 python 控制包的错误奈奎斯特图
- django - 查询继承的模型
- python - 检查用户输入是否匹配(随机)整数的任何数字
- python - 芹菜任务被“接收”是什么意思?当所有 celery 工人都被阻止时,未“接收”的新任务会发生什么?
- angular - 打字稿 - 键入一个接口?
- regex - Puppet 正则表达式(在引号之间的 var 中抓取路径)
- sql - SQL Query 从表中的每个批次中选择顶部和底部的行