js自定义localStorage的过期时间----完整代码解析

前言:
我们知道localStorage如果设置了,那么默认是永久有效的,除非手动进行删除。

手动删除:可以在谷歌浏览器控制台的Application => Local Storage 中找到自己要删除的文件/域名中的某一项数据双击进行清空删除即可。

自定义过期时间:
默认localStorage的api中时不支持设置过期时间的,所以我们只能对localStorage进行二次封装。

自定义过期时间实现的思路:
1、在设置localStorage数据的时候传入过期时间参数,然后自定义个键名来保存过期时间,这个键名要和设置数据的键名有关联。
2、获取localStorage数据的时候先判断过期时间键名保存的时间和当前时间的毫秒数,如果当前时间的毫秒数还大的话就表示数据过期了,那么就删除过期数据

注意点:
1、存储的值可能是数组/对象,不能直接存储,需要转换,使用 JSON.stringify()。
2、设置到localStorage中的数据格式都为字符串类型,就算你设置时是数字类型,获取的时候也是字符串类型了。

具体代码实现:

class storage {
  constructor() {
    this.source = window.localStorage;
    this.initClear();
  }

  /**
    * 初始化清除已经过期的数据
    */
  initClear(){    
    // const reg = new RegExp("__expires__");
    const reg = /__expires__/;
    let data = this.source;
    let list = Object.keys(data);
    if(list.length > 0){
      list.forEach((key) => {
        // 如果为非包含__expires__键名的key进行判断清除过期的
        if( !reg.test(key)){
          let now = Date.now();
          let expires = data[`${key}__expires__`];
          if (now >= expires ) {
            this.remove(key);
          }
        }
      })
    };
  }

  /**
    * set 存储方法
    * @ param {String} 	key 键名
    * @ param {String} 	value 键值
    * @ param {String} 	expired 过期时间,以分钟为单位,非必须。(不传则为永久有效)
    */
  set(key, value, expired) {    
    let source = this.source;
    source[key] = JSON.stringify(value);
    if (expired !== undefined){
      // // 过期时间单位为天
      // source[`${key}__expires__`] = Date.now() + 1000 * 60 * 60 * 24 * expired
      // // 过期时间单位为小时
      // source[`${key}__expires__`] = Date.now() + 1000 * 60 * 60 * expired
      // 过期时间单位为分钟
      source[`${key}__expires__`] = Date.now() + 1000 * 60 * expired;
    };
  }

  /**
    * get 获取方法
    * @ param {String} 	key 键名
    * @ return  如果没过期则返回数据,否则返回null
    */
  get(key) {    
    const source = this.source;
    const expires = source[`${key}__expires__`];
    // 获取前把已经过期的数据删除掉
    if (expires) {
      const now = Date.now();
      if ( now >= expires ) {
        this.remove(key);
        return null;
      }
    }
    // 获取数据
    const value = source[key] ? JSON.parse(source[key]) : null;
    return value;
  }

  /**
    * remove 删除方法
    * @ param {String} 	key 键名  非必须 (不传则删除所有)
    */
  remove(key) {
    if (key) {
      // localStorage自带的removeItem()方法
      this.source.removeItem(key);
      this.source.removeItem(`${key}__expires__`);
      // delete data[key];
      // delete data[`${key}__expires__`];
    } else {
      // 清除所有,localStorage自带的clear()方法
      this.source.clear();
    }
    
  }
}

let myLocalStorage = new storage()

myLocalStorage.set('name', 'winne')
myLocalStorage.set('age', '100', 30)
myLocalStorage.set('num', '88', 0)
myLocalStorage.set('oneMinute', '22', 1)
myLocalStorage.set('obj', {name: 'xf'}, 10)

console.log(myLocalStorage.get('name')) // 'winne'
console.log(myLocalStorage.get('age')) // '100'
console.log(myLocalStorage.get('num')) // null
console.log(myLocalStorage.get('oneMinute')) // '22'
console.log(myLocalStorage.get('obj')) // {name: "xf"}
// myLocalStorage.remove('age')
// myLocalStorage.remove()

运行图:
在这里插入图片描述

资料参考:
https://blog.csdn.net/weixin_43254766/article/details/83618630

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章