2017-03-04 54 views
0

我(使用严格模式)保存元素像这样的localStorage:的Javascript localStorage的零错误

localStorage.setItem(String(index), JSON.stringify([name, score]));

然后我写了一个方法检查是否一个新的得分比得救的更大:

// Returns index where to place the score and return -1 if no new highscore 
    function isHighScore(score) { 
    console.log("called"); 
    for (var i = 0; i < 3; i++) { 
     if (localStorage.getItem(String(i)) == null) { 
      return i; // No highscore yet at this position => new Highscore 
     } 
     else{ 
      var indexObject = JSON.parse(localStorage.getItem(String(i))); 
      console.log(indexObject); 
      if(indexObject[1] < score){ // Checking if new score is higher than currently at this index 
       return i; // Returning index if new highscore 
      } 
     } 
    } 
    return -1; // checked all entries no new highscore 
} 

但我得到这个下面的输出(节能与NAME = “名称” 的例子后得分= 0):

called

["name", 0]

null

Uncaught TypeError: Cannot read property 1 of null

这是怎么发生的?我已经在检查数值是否为null,那么如果通过检查localStorage.getItem(String(i)) == null),该如何通过?

+1

你可以用[mcve]更新问题吗? (遗憾的是,它必须是不可运行的,因为Stack Snippets不允许你使用本地存储,尽管你可以创建一个可运行的jsFiddle并且链接到它**提供**你还包含了所有的代码问题。) –

+0

@TJCrowder好的我会这样做 –

+1

下一次。没有必要在这种情况下,因为它发生了! :-) –

回答

5

我怀疑如果您使用浏览器的devtools来查看本地存储的内容,您会发现"1"的值为"null"

这解释了症状,因为

if (localStorage.getItem(String(i)) == null) { 

...是false如果localStorage.getItem(String(i))回报"null",但随后

var indexObject = JSON.parse(localStorage.getItem(String(i))); 

...将设置indexObjectnull

+1

真棒,只是修复它:) –