本地存储
const store = {
set: function(name, value, day) {
let d = new Date()
let time = 0
day = (typeof(day) === 'undefined' || !day) ? 1 : day //时间,默认储存1天
time = d.setHours(d.getHours() + (24 * day))
localStorage.setItem(name, JSON.stringify({
data:value,
time: time
}))
},
get:function(name) {
let data = localStorage.getItem(name)
if(!data) {
return null
}
let obj = JSON.parse(data)
if(new Date().getTime() > obj.time) { //过期
localStorage.removeItem(name)
return null
}else {
return obj.data
}
},
clear:function(name) { //清空
if(name) {
localStorage.removeItem(name)
}else { //清空全部
localStorage.clear()
}
}
}
网友评论