新手试图让localStorage工作

时间:2016-04-13 14:16:18

标签: javascript local-storage

除了undefined之外,我无法获得以下代码。我做得不对劲?我也不确定得分函数的工作原理。到目前为止,我只编写了vanilla function doSomething() {}方法。谢谢。

var score = score || {};

score = {
  saveHighScore: function(tally) {
    var high_score = localStorage.high_score;
    if (typeof high_score == 'number') {
      if (tally > high_score) {
        localStorage.high_score = tally;
      }
    } else {
      localStorage.high_score = tally;
    }
  },
  getHighScore: function() {
    var high_score = localStorage.high_score;
    if(typeof high_score !== 'number') {
      high_score = 0;
      localStorage.high_score = high_score;
    }
    return high_score;
  }
}

window.console.log("Score: ", score.getHighScore());

1 个答案:

答案 0 :(得分:1)

您的问题是本地存储将值存储为字符串键/值对,因此您需要parseInt: -

var score = score || {};

score = {
  saveHighScore: function(tally) {
    var high_score = localStorage.high_score;
    if (typeof high_score == 'number') {
      if (tally > high_score) {
        localStorage.high_score = tally;
      }
    } else {
      localStorage.high_score = tally;
    }
  },
  getHighScore: function() {
    var high_score = parseInt(localStorage.high_score);
    if(typeof high_score !== 'number') {
      high_score = 0;
      localStorage.high_score = high_score;
    }
    return high_score;
  }
}

score.saveHighScore(100)

window.console.log("Score: ", score.getHighScore());
  

我不知道为什么,但我重新加载了上面发布的相同代码   在控制台中返回得分:0。

它返回0的原因是在getHighScore内部,它从本地存储中检索值并进行比较以查看它是否不是数字,如果不是,则将其设置为{ {1}}。由于本地存储将所有值保存为字符串,因此始终将您的值设置为0

  

我不确定分数功能是如何工作的,

这些只是对象内部的函数。