本地存储中的高分 - Javascript

时间:2017-12-17 19:09:23

标签: javascript arrays json for-loop local-storage

我在javascript中创建游戏并希望在高分榜中呈现5个最佳分数。当我到达最终屏幕时,我只会看到最新/最佳分数。我究竟做错了什么?

let result = {userName: user, score: timeScore}

let highscore = []

highscore.push(result)

highscore.sort(function (a, b) {
return (a.timeScore - b.timeScore)
})

let hsTable = document.getElementById('highscores')

window.localStorage.setItem('highscore', JSON.stringify(highscore))

let retrievedScores = JSON.parse(window.localStorage.getItem('highscore'))


for (let i = 0; i < 5; i++) {
    hsTable.innerHTML += '<tr><td>' + retrievedScores[i].userName + '</td><td>' + retrievedScores[i].score + '</td></tr>'
  }

1 个答案:

答案 0 :(得分:2)

您将最新分数保存在所有其他分数上。获得旧的分数,排序,获得前5个最高分,并存储它:

const result = {userName: user, score: timeScore}

const savedScores = localStorage.getItem('highscore') || '[]' // get the score, or the initial value if empty

const highscores = [...JSON.parse(savedScores), result] // add the result
  .sort((a, b) => b.score- a.score) // sort descending
  .slice(0, 5) // take highest 5

localStorage.setItem('highscore', JSON.stringify(highscores)) // store the scores