每天get几个JavaScript小技巧(三)

2022-05-26  本文已影响0人  肖青荣
本地存储
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()
    }
  }
}
上一篇下一篇

猜你喜欢

热点阅读