2022-02-24--localStorage 设置和获取

2022-02-24  本文已影响0人  派大星星
//向本地存储数据
function setLocalStorage(key, value, days) {
    // 设置过期原则
    if (!value) {
        localStorage.removeItem(key)
    } else {
        var Days = days || 1; // 默认保留1天
        var exp = new Date();
        localStorage[key] = JSON.stringify({
            value,
            expires: exp.getTime() + Days * 24 * 60 * 60 * 1000
        })
    }
}

eg:
setLocalStorage('JSXM',data.data);

//获取本地存储数据
function getLocalStorage(key) {
    try {
        let o = JSON.parse(localStorage[key])
        if (!o || o.expires < Date.now()) {
            return false
        } else {
            return o.value
        }
    } catch (e) {
        // 兼容其他localstorage
        console.log(e)
        return localStorage[key]
    } finally {
    }
}
 
eg:
getLocalStorage('JSXM')
上一篇下一篇

猜你喜欢

热点阅读