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
  }
}
相關文章
相關標籤/搜索