我(使用严格模式)保存元素像这样的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)
,该如何通过?
你可以用[mcve]更新问题吗? (遗憾的是,它必须是不可运行的,因为Stack Snippets不允许你使用本地存储,尽管你可以创建一个可运行的jsFiddle并且链接到它**提供**你还包含了所有的代码问题。) –
@TJCrowder好的我会这样做 –
下一次。没有必要在这种情况下,因为它发生了! :-) –