wingmeng / front-end-quiz

前端小测试答题收集
0 stars 0 forks source link

JS基础测试32:cookie 及 localStorage 操作 #14

Open wingmeng opened 5 years ago

wingmeng commented 5 years ago

题目:

image


我的回答:

// 存储时加个时间戳 localStorage.setItem('userid', JSON.stringify({ data: 1, stamp: Date.now() + expires }));

// 取值时进行判断 var store_userid = JSON.parse(localStorage.getItem('userid')); var uidStamp = store_userid.stamp; var userid;

if (uidStamp <= Date.now()) { // 过期 localStorage.removeItem('userid'); } else { userid = store_userid.data; }

wingmeng commented 5 years ago

自我评分:良好

优秀、良好、一般、差劲

不足之处:

  1. 未对 localStorage 进行组件化封装;
  2. 获取 cookie 的方式不够优雅

学习收获:

  1. 练习 cookie、localStorage 操作;
  2. localStorage 代替 cookie 方案
wingmeng commented 5 years ago

localStorage polyfill (使用 cookie 模拟)

!window.localStorage && !function(win) {
  var thousandYears = 1e3 * 365 * 24 * 36e5;

  function getCookies() {
    return document.cookie.match(/([^;=]+)=([^;]+)/g) || [];
  }

  function getExpires(flag) {
    flag = flag || 1;

    return 'expires=' +
      (new Date((+new Date()) + thousandYears * flag)).toUTCString();
  }

  function get(key) {
    var cookies = getCookies();

    for (var i = 0; i < cookies.length; i++) {
      var param = cookies[i].match(/^\s*([^=]+)=(.+)/);

      if (param[1] === String(key)) {
        return decodeURIComponent(param[2]);
      }
    }

    return null;
  }

  function set(key, value, isExpired) {
    document.cookie = [
      key + '=' + encodeURIComponent(value),
      getExpires(isExpired ? -1 : 1),
      'path=/'
    ].join('; ');
  }

  function remove(key) {
    set(key, '', true);
  }

  function clear() {
    var cookies = getCookies();

    for (var i = 0; i < cookies.length; i++) {
      var key = cookies[i].match(/^\s*([^=]+)/)[1];
      remove(key);
    }
  }

  // 注册到 window 对象上
  win.localStorage = {
    getItem: get,
    setItem: set,
    removeItem: remove,
    clear: clear
  };
}(window);