[英]Uncaught SyntaxError: Unexpected end of JSON input : at JSON.parse (<anonymous>)
it throws error when I try to parse localStorage['highscores"]当我尝试解析 localStorage['highscores"] 时它会引发错误
if (localStorage["highscores"] == undefined) {
localStorage["highscores"] = [];
}
var highscores = JSON.parse(localStorage["highscores"]) || [];
I have not defined localStorage['highscores"] so I try to check it and if it is undefined define it, bcs if it is full I want to save it's information in localStorage['highscores"] and add more information too.我还没有定义 localStorage['highscores"] 所以我尝试检查它,如果它未定义,则定义它,如果它已满,我想将它的信息保存在 localStorage['highscores"] 中并添加更多信息。
any ideas?有任何想法吗?
Local Storage may only hold strings.本地存储只能保存字符串。 When you set non-strings to it, it'll be coerced to a string.
当您为其设置非字符串时,它将被强制转换为字符串。
When arrays are converted to strings, .join(',')
is called on the string.当 arrays 转换为字符串时,对字符串调用
.join(',')
。 The empty array will be converted into the empty string:空数组将转换为空字符串:
console.log(String([]) === '');
Which is not JSON-parseable.这不是 JSON 可解析的。
Save the JSON-stringified version of the empty array instead.改为保存空数组的 JSON 字符串化版本。
if (localStorage.highscores === undefined) {
localStorage.highscores = '[]';
}
or或者
if (localStorage.highscores === undefined) {
localStorage.highscores = JSON.stringify([]);
}
When in doubt, always use JSON.stringify
/ JSON.parse
when transferring to and from Local Storage.如有疑问,请始终在与本地存储之间传输时使用
JSON.stringify
/ JSON.parse
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.