删除我的本地存储

时间:2016-02-22 18:36:38

标签: javascript jquery

拥有以下本地存储脚本,我正在寻找一种方法,以便在7天后,如果余额为= 0,余额将被重置。我应该怎么做?

var balance = localStorage.getItem('balance');

if (balance === null) {
    // Not found, set value from database or wherever you get the value
    balance = 50; // Or whatever value
} else {
    // Convert the retrieved value to a number, since
    // localStorage stores everything as string.
    balance = +balance; 
}

function updateBalance(newBalance) {
        localStorage.setItem('balance', newBalance);
        balance = newBalance;
    }

1 个答案:

答案 0 :(得分:1)

您需要将日期与余额一起存储。由于localStorage只存储字符串,因此您可以使用JSON将balance + date对象转换为字符串。像这样:

var balanceObj = {
    balance: 0,
    transactionDate: new Date()
};

存储它:

localStorage.balance = JSON.stringify( balanceObj );

检索它:

balanceObj = JSON.parse( localStorage.balance );