Adding a high score to local storage

后端 未结 5 1752
轻奢々
轻奢々 2021-01-06 16:37

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

相关标签:
5条回答
  • 2021-01-06 16:58

    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);
    }
    
    0 讨论(0)
  • 2021-01-06 17:12

    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);
    }
    
    0 讨论(0)
  • 2021-01-06 17:13

    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?

    0 讨论(0)
  • 2021-01-06 17:21

    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.

    0 讨论(0)
  • 2021-01-06 17:21
    if (score > parseInt(localStorage.getItem('highscore'), 10)) {
      localStorage.setItem('highscore', score);
    }
    

    convert into int before comparing. its string

    0 讨论(0)
提交回复
热议问题