I have the following used to create a dummy high score table if if localscores doesn’t exist in local storage:
if (localStorage.getItem("localScores") === null) {
highscores = [
{user: "Player 1", score: 100},
{user: "Player 2", score: 90},
{user: "Player 3", score: 80},
{user: "Player 4", score: 70},
{user: "Player 5", score: 60},
{user: "Player 6", score: 50},
{user: "Player 7", score: 40},
{user: "Player 8", score: 30},
{user: "Player 9", score: 20},
{user: "Player 10", score: 10}
];
localStorage['localScores']=JSON.stringify(highscores);
console.log("doesn't exist")
}
else{
highscores = JSON.parse(localStorage['localScores']);
console.log("exists")
}
I always want to maintain 10 scores so I have this to add a score, where username and total are the name entered and score achieved:
highscores.push({user: username, score: total});
highscores.sort(function(a,b){ return b.score - a.score});
delete highscores[10];
localStorage['localScores']=JSON.stringify(highscores);
console.log(highscores);
Everything is fine until I reload the game and the first function runs, it seems to add null value to the highscores array. So if I add 5 additional scores I will have 3 null values in the array?
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, null, null, null, null, null]
This leads me to believe either the line where I evaluate if the localscores exists is wrong
(localStorage.getItem(“localScores”) === null)
Or where I delete the 11th element in the array is wrong
delete highscores[10];
Or there’s some other issue I don’t see, if anyone knows what’s going on I’d very much appreciate some help.
When you call
deleteon an Array instance, you don’t actually make the array shorter, you just replace the value at the specified index withundefined.If the length of
highscoresshould always be no greater than 10, and the item to be removed will always be the last, you could simply usehighscores.length = 10.You could also use
highscores = highscores.slice(0,10);, but as jfriend00 pointed out, it does involve the extra overhead of creating a new array.Although, I feel compelled to mention that the performance hit of creating a new array is really just a drop in the bucket compared to the amount of work the browser will be doing to encode/decode JSON and read/write from localStorage, which is notoriously slow.