localStorage函数返回NaNs值

时间:2018-03-22 09:57:42

标签: javascript local-storage

I am trying to display the shortest time taken to click a shape. However the `localStorage` function is returning a `NaN` value instead of the required Number value. How can I tweak the code to return a number value. 

由于

document.getElementById("shapes").onclick = function() {

    document.getElementById("shapes").style.display = "none";

    shapeAppearDelay();

    var end = new Date().getTime();

    var timeTaken = (end - start) / 1000;

    document.getElementById("timeTaken").innerHTML = "Time taken: " + timeTaken + "s";

    var timeTaken = (end - start) / 1000;

    if (localStorage.shortestTimeTaken) {

        if (timeTaken < Number(localStorage.shortestTimeTaken)) {

            localStorage.shortestTimeTaken = timeTaken;
        }

    } else {
        localStorage.shortestTimeTaken = timeTaken;
    }
    document.getElementById("shortestTimeTaken").innerHTML = "Shortest time taken: " + localStorage.shortestTimeTaken + "s";
}

3 个答案:

答案 0 :(得分:0)

要在localStorage中设置值,请使用setItem

localstorage.setItem("shortestTimeTaken",timeTaken)

获取价值,getItem

localstorage.getItem("shortestTimeTaken")

答案 1 :(得分:0)

如果要在localStorage中保存shortestTimeTaken值,则可以使用localStorage.getItem('shortestTimeTaken')获取数据。 LocalStorage有2个函数setItem('key','value')&amp;的GetItem( '钥匙')

答案 2 :(得分:0)

使用localStorage的正确方法是使用setItem()getItem

...
if (timeTaken < Number(localStorage.getItem("shortestTimeTaken"))) {
    localStorage.setItem("shortestTimeTaken",timeTaken);
}
...