【问题标题】:Highscore list comes out as undefined高分列表显示为未定义
【发布时间】:2017-12-05 22:49:58
【问题描述】:

我完成了一个学校游戏,它运行良好。但我需要将每场比赛的得分存储在本地存储中。我可以呈现个人分数,但如果我想要一个包含分数的数组,则值是“未定义的”。不知道我在哪里弄错了,因为本地存储显示了数据,尽管两次... 有没有机会从你那里得到提示?

在游戏开始时,我想显示分数,如果有的话。我这样做:

let score = document.querySelector('#score')
let scores = []
if (scores.length > 0) {
  let score = document.querySelector('#score')
  let extract = JSON.parse(window.localStorage.getItem('scores'))
  let highscore = document.createTextNode(extract.Nickname + ' - ' + 
  extract.Score)
  score.appendChild(highscore)
}

当玩家完成游戏并得到所有正确答案后,我使用此代码推送对象:

window.scoreNickname = document.getElementById('name').value
window.scoreTime = seconds + 's ' + totalTimeSum % 1000 + 'ms'
let scoreData = {
    Nickname: window.scoreNickname,
    Score: window.scoreTime
}
scores.push(scoreData)
window.localStorage.setItem('scores', JSON.stringify(scores))
let extract = JSON.parse(window.localStorage.getItem('scores'))
let highscore = document.createTextNode(extract.Nickname + ' - ' + 
extract.Score)
score.appendChild(highscore)

但是我让我们不确定。在本地存储中,我有以下信息:

scores: [{"Nickname":"Adam","Score":"18s768ms"},
{"Nickname":"Adam","Score":"18s768ms"}

【问题讨论】:

  • let scores = [] if (scores.length > 0) { 永远不会执行条件块
  • extract 将是一个数组,就像 scores 一样。它没有.Nickname 属性

标签: javascript node.js dom local-storage


【解决方案1】:

尝试:

let extract = window.localStorage.getItem('scores');

我认为你不需要 JSON.parse 一个 JSON 对象

【讨论】:

  • 是的。 Localstorage 存储字符串(在本例中为 JSON 字符串),而不是对象。
猜你喜欢
  • 2020-06-02
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多