Question

if localStorage["BestScore"] = undefined;
{
localStorage["BestScore"]=0; 
maxScore=0;
}

 var maxScore=localStorage["BestScore"]; 
  var newScore=false
  function drawScore(score) {
    if (newScore == true && score < maxScore) {
      newScore = false;
    }
    if (score > maxScore) {
      newScore = true;
      localStorage["BestScore"] = score;
      if ([5, 10, 15, 20].indexOf(score) !== -1) {
        play(sndMedal);
      } else { 
        play(sndGain);
      }
    }

This code is to set the max score and then store it but it doesn't seem to set the local storage to 0 if undefined.

Était-ce utile?

La solution 2

However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:

if (typeof localStorage["BestScore"] === "undefined") {
    localStorage["BestScore"] = 0;
}

It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.

Autres conseils

if localStorage["BestScore"] = undefined;

should be:

if( typeof localStorage["BestScore"] === 'undefined' )
if localStorage["BestScore"] = undefined;

should be ==

else you are assigning, not comparing.

use == or === as a comparison operator, then it should be fine

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top