Javascript LocalStorage Null Bug

Mat*_*ann 0 javascript null local-storage

我在这样的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
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下输出(在保存示例后使用name ="name"和得分= 0):

叫

["名字",0]

空值

未捕获的TypeError:无法读取1null的属性

怎么会发生这种情况?我已经在检查价值是否null如此,如果检查,如何通过第一个localStorage.getItem(String(i)) == null)?

T.J*_*der 5

我怀疑如果你使用浏览器的devtools来查看本地存储中的内容,你会找到一个"1"带有值的条目"null".

这解释了症状,因为

if (localStorage.getItem(String(i)) == null) {
Run Code Online (Sandbox Code Playgroud)

...... false如果是localStorage.getItem(String(i))回归"null",那么

var indexObject = JSON.parse(localStorage.getItem(String(i)));
Run Code Online (Sandbox Code Playgroud)

......将设置indexObject为null.