首页 > 解决方案 > 未捕获的 SyntaxError:JSON 输入意外结束:在 JSON.parse()

问题描述

当我尝试解析 localStorage['highscores"] 时它会引发错误

if (localStorage["highscores"] == undefined) {
    localStorage["highscores"] = [];
}
var highscores = JSON.parse(localStorage["highscores"]) || [];

我还没有定义 localStorage['highscores"] 所以我尝试检查它,如果它未定义,则定义它,如果它已满,我想将它的信息保存在 localStorage['highscores"] 中并添加更多信息。

有任何想法吗?

标签: javascriptarraysjsonparsinglocal-storage

解决方案


本地存储只能保存字符串。当您为其设置非字符串时,它将被强制转换为字符串。

当数组转换为字符串时,.join(',')在字符串上调用。空数组将转换为空字符串:

console.log(String([]) === '');

这不是 JSON 可解析的。

改为保存空数组的 JSON 字符串化版本。

if (localStorage.highscores === undefined) {
    localStorage.highscores = '[]';
}

或者

if (localStorage.highscores === undefined) {
    localStorage.highscores = JSON.stringify([]);
}

如有疑问,在与本地存储之间传输时始终使用JSON.stringify/ 。JSON.parse


推荐阅读