鍍金池/ 問答/HTML/ localStorage失效問題

localStorage失效問題

如何給localStorage添加生命周期?

每天0點就刪除掉,第二天接口的新數(shù)據(jù)再次存入localStorage

依次循環(huán),每天都會有新的數(shù)據(jù)存入,而舊的會在當天24點前就會被刪掉

原生js該怎么寫才對?

回答
編輯回答
逗婦惱

vsdavv

2017年4月22日 19:39
編輯回答
吢涼

寫個日期進去,每次讀取時和當前日期判斷下是否過期,過期就更新

2017年5月6日 13:54
編輯回答
亮瞎她

存的時候給個時間值,每次啟動的時候,把過期的給刪除
存的數(shù)據(jù)

localStorage.setItem('data', JSON.stringify({
    date: Date.now(),
    item: {name:'你好'}
}))

刪除過期數(shù)據(jù)

var data = JSON.parse(localStorage.getItem('data'))
// isStale:過期的邏輯
if (isStale(data.date)) {
    localStorage.removeItem('data')
}
2018年4月8日 12:59
編輯回答
法克魷

這種情況用本來就有生命周期的cookie不是更好嗎

2018年9月16日 18:49
編輯回答
萌吟

這種需求,最好就是服務端websocket主動推送,覆蓋客戶端localstorage

2018年2月1日 02:39
編輯回答
病癮
function getTime(type,current) {  //獲取當天日期前一天
    let time = new Date();
    let date = time.getDate()-current||0;
    return type + date;
};
let str = this.getTime('preferential');返回 'preferential23'
    if (!localStorage.getItem(str)) { //檢查今天的localStorage在不在,不再就存,讀取也是一樣;
    localStorage.setItem(str,'122')
}

刪除昨天的數(shù)據(jù)的話
let str = this.getTime('preferential',1);返回 'preferential22';
if(localStorage.getItem(str)){
    localStorage.removeItem(str) //即可刪除昨天的數(shù)據(jù)
}
2017年9月24日 09:09