localStorage封装

export const storage = () => {
  let set;
  let get;
  if(window.localStorage) {
    set = (name, value) => {
      return window.localStorage.setItem(name, value);
    }
    get = (name) => {
      return window.localStorage.getItem(name);
    }
  } else {
    set = (name, value, permanent = true) => {
      let c = name + '=' + value;
      var d = new Date();
     d.setDate(d.getDate() + 1000);
     d.toGMTString();
      if(permanent) {
        c += (';expires=' + d)
      }
      return document.cookie = c;
    }
    get = () => {
      //先查询cookie是否为空,为空就return ""
      if ( document.cookie.length > 0){  
        let start = 0;
        let end = 0;
        //通过String对象的indexOf()来检查这个cookie是否存在,不存在就为 -1
        start = document.cookie.indexOf(c_name + '=')
      if (start != -1){ 
        start = start + c_name.length + 1;
        end = document.cookie.indexOf(";", start)
        if (end == -1) end = document.cookie.length  
        return unescape(document.cookie.substring(start, end))  //通过substring()得到了值。想了解unescape()得先知道escape()是做什么的,都是很重要的基础,想了解的可以搜索下,在文章结尾处也会进行讲解cookie编码细节
      } 
    }
    return ''
    }
  }
  return {
    get, set
  }
}

 

posted on 2019-09-20 17:18  KyleLjc  阅读(173)  评论(0编辑  收藏  举报

导航