【问题标题】:Uncaught SyntaxError: Unexpected end of JSON input : at JSON.parse (<anonymous>)未捕获的 SyntaxError:JSON 输入意外结束:在 JSON.parse (<anonymous>)
【发布时间】:2023-03-23 11:19:01
【问题描述】:

当我尝试解析 localStorage['highscores"] 时会抛出错误

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

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

有什么想法吗?

【问题讨论】:

  • 应该是if (typeof localStorage["highscores"] == 'undefined') {
  • 预期同样的错误
  • @JaydeepChauhan 这在 99.9% 的情况下应该没有区别。

标签: javascript arrays json parsing local-storage


【解决方案1】:

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

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

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

这不是 JSON 可解析的。

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

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

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

如有疑问,请始终使用JSON.stringify/JSON.parse 与本地存储进行传输。

【讨论】:

  • 您可能已经将一些无效的 JSON 放入本地存储。尝试先清除本地存储。
  • 清除localstorage时出现空的错误
  • 在这里工作得很好:jsfiddle.net/e5aq79Lr 如果它不适合你,你必须有其他代码弄乱了不在问题中的存储 - 或者你没有从答案中复制代码正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 2021-05-01
  • 2020-01-08
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多