【问题标题】:Adding a high score to local storage向本地存储添加高分
【发布时间】:2017-03-11 16:01:34
【问题描述】:

我想为我的游戏添加一个高分。现在我有这个:

var score = 0;
var highscore = 0;

分数变量有效,但每当我得到喜欢的点数时,总分达到 60 分时,使用console.log(highscore) 检查时,它表示高分仍然为零。

我有这个来存储高分:

if (score > localStorage.getItem("highscore")) {
  localStorage.setItem("highscore", score);
}

这不能正常工作,但它也不会给出任何错误。

【问题讨论】:

  • 只是对您的 pastebin 的一个想法,您可能希望将变量转换为对象,这会很有帮助:)

标签: javascript html local-storage


【解决方案1】:

试试这个:

var score = 0;
var highscore = localStorage.getItem("highscore");

if(highscore !== null){
    if (score > highscore) {
        localStorage.setItem("highscore", score);      
    }
}
else{
    localStorage.setItem("highscore", score);
}

【讨论】:

  • 不,localStorage 存储字符串!
【解决方案2】:

除了parseInt,你还需要先在localStorage上设置init值,因为localStorage.getItem("highscore",10)如果没有设置就不会返回10作为默认值

var score = 0;
var highscore = 0;
localStorage.setItem("highscore",0);

因为当你检查时

if (score > parseInt(localStorage.getItem("highscore"))) {
  localStorage.setItem("highscore", score);
}

如果项目尚未设置,localStorage.getItem("highscore") 将返回 null。或者你也可以这样做:

var storagedHighScore = localStorage.getItem("highscore");
if (storagedHighScore  || score > parseInt(storagedHighScore)) {
  localStorage.setItem("highscore", score);
}

【讨论】:

    【解决方案3】:

    您需要从 localStorage 中检索值

    highscore = +localStorage.getItem("highscore")
    

    或一些等效的代码。 localStorage 中的项目不跟踪同名的全局变量。

    【讨论】:

      【解决方案4】:
      if (score > parseInt(localStorage.getItem('highscore'), 10)) {
        localStorage.setItem('highscore', score);
      }
      

      在比较之前转换为 int。它的字符串

      【讨论】:

      • 仍然无法正常工作,您可以在这里查看我的孔代码pastebin.com/sgZS8tzz
      • 你能分享 jsfiddle 或 plnkr 链接吗?我无法访问 pastebin
      • 这是一个空洞游戏,这是一个脚本,但是我可以把它放在 jsfiddle 中,你去jsfiddle.net/unb8yLj3
      • 这无关紧要,因为如果score 是数字,它应该被强制转换为数字。
      • @Qantas94Heavy :- 我的坏。你说的对。它会自动转换。
      【解决方案5】:

      我刚刚在http://jsfiddle.net/unb8yLj3/ 中查看了您的代码,但我找不到您在哪个部分增加了分数,所以当这部分代码运行分数为 0 和 localStorage.getItem("highscore") 是 10,因此它不设置高分。

      if (score > localStorage.getItem("highscore")) {
                      localStorage.setItem("highscore", score);
      
                  }
      
        }
      

      有没有另外一个js文件确实提高了分数?

      【讨论】:

        猜你喜欢
        • 2012-08-23
        • 2018-05-31
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-24
        相关资源
        最近更新 更多