it throws error when I try to parse 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.
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. The empty array will be converted into the empty string:
console.log(String([]) === '');
Which is not JSON-parseable.
Save the JSON-stringified version of the empty array instead.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.