本地存储最佳分数未定义/无值

时间:2014-03-18 10:17:29

标签: javascript html5 local-storage

if (typeof localStorage["BestScore"] === 'undefined') {
    localStorage["BestScore"] = 0;
    var maxScore=0;
}     
else {
    var maxScore= localStorage["BestScore"] 
}

此代码尝试检查本地存储最佳分数是否为undefined/no value,如果是,则将maxscore设置为0如果它具有值,则将maxscore设置为该值。出于某种原因,这段代码无效,请帮助。

2 个答案:

答案 0 :(得分:0)

这就是我使用的。首先检查存储是否可行,然后检查您的对象是否存在。所以...

if (typeof (Storage) !== "undefined") {
    if (!localStorage.BestScore) {
        localStorage.BestScore = 0;
    }

    var maxScore = localStorage.BestScore; 
}

答案 1 :(得分:-1)

你错过了一个;在第6行。

if (typeof localStorage["BestScore"] === 'undefined') {
  localStorage["BestScore"] = 0;
  var maxScore=0;
}else {
  var maxScore= localStorage["BestScore"] ;
}