【问题标题】:Highscore in local storage - Javascript本地存储中的高分 - Javascript
【发布时间】:2018-05-31 05:00:50
【问题描述】:

我正在用 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>'
  }

【问题讨论】:

  • 可能是您的排序功能:这些字段称为分数,而不是 timeScore。 highscore.sort(function (a, b) { return (a.score - b.score) })
  • 是我遗漏了什么还是您只向数组高分添加了一条记录?

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


【解决方案1】:

您将最新的分数保存在所有其他分数之上。获取旧分数,排序,取前 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多