Adding a high score to local storage

假装没事ソ 提交于 2019-12-19 11:52:10

问题


I want to add a high score to my game. Right now I have this:

var score = 0;
var highscore = 0;

The score variable works but whenever I get like points so total of 60 points it says the high score is still zero when checking it using console.log(highscore).

I have this to store the high score:

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

This does not work properly, but it also doesn't give any errors.


回答1:


In addition to the parseInt, you need to set the init value on the localStorage first because localStorage.getItem("highscore",10) doesn't returns 10 as default value if is not setted

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

Because when you check

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

The localStorage.getItem("highscore") will return null if the item is not setted yet. Or you can also do:

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



回答2:


Try this:

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

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



回答3:


You need to retrieve the value from localStorage with

highscore = +localStorage.getItem("highscore")

or some equivalent code. Items in localStorage don't track the global variables with the same names.




回答4:


I just reviewed your code in http://jsfiddle.net/unb8yLj3/ and i couldn't find in what part you increase the score so when this part of code run score is 0 and localStorage.getItem("highscore") is 10 therefore it doesn't set highscore.

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

            }

  }

Is there another js file that does increase the score?




回答5:


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

convert into int before comparing. its string



来源:https://stackoverflow.com/questions/29370017/adding-a-high-score-to-local-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!