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.