• JS本地存储技术


    localStorage

    1. 特点
      ① 永久存储、除非手动删除
      ② 最大可存储5M
      ③ 不参与服务器通信
      ④ 只能存储字符串

    2. localStorage.setItem(key, value);
      
      • 1
    3. localStorage.getItem(key);
      
      • 1
    4. localStorage.removeItem(key);
      
      • 1
    5. 清空所有

      localStorage.clear();
      
      • 1

    cookie

    1. 特点
      ① 只有关闭整个浏览器,数据才会清除
      ② 可设置过期时间
      ③ 最大可存储4KB,最多可存储50条数据
      ④ 只能存储字符串


    2. 防止中文乱码问题,可以利用encodeURIComponent、decodeURIComponent进行编码和解码操作

      document.cookie = `username=${encodeURIComponent('五五')};`;
      
      • 1
    3. // 取出所有
      console.log(document.cookie);
      // 函数封装:通过key取出指定的cookie
      function getCookieByKey(searchKey) {
         const allCookie = document.cookie.split('; ');
         for(let i = 0; i < allCookie.length; i++) {
             const item = allCookie[i].split('=');
             if (item[0] === searchKey) {
                return decodeURIComponent(item[1]);
             }
         }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12

    4. 利用存的方式直接将该条语句覆盖即可

    5. 设置过期时间
      expires必须传入日期格式

      // 在n天后过期
      function expiresAfterDay(n) {
      	const d = new Date();
      	d.setDate(d.getDate() + n);
      	return d;
      }
      document.cookie = `username=${encodeURIComponent('五五')};expires=${expiresAfterDay(2)}`; //  2天后过期
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7

    6. 设置过去的时间即可

      document.cookie = `username=;expires=${new Date(0)}`;
      
      • 1
    7. 限制访问路径
      ① 不设置的话,默认为当前页面加载的路径
      ② path必须与当前页面加载的路径一致,如果不一致,则访问不到

      document.cookie = `username=${encodeURIComponent('五五')};path=/otherPath`; // 模拟路径不同的情况,这时获取该条cookie为空,因为路径不一致
      
      • 1
    8. 限制访问域名
      ① 不设置的话,默认为当前页面加载的域名
      ② domain必须与当前页面加载的域名一致,如果不一致,则cookie设置失败

      document.cookie = `username=${encodeURIComponent('五五')};domain=abc`;
      
      
      • 1
      • 2
    9. secure
      ① 不设置secure,http/https协议加载的页面都可以设置cookie
      ② 设置secure,只有https协议加载的页面才可以设置cookie

      document.cookie = `username=${encodeURIComponent};secure`;
      
      • 1

    sessionStorage

    1. 特点
      ① 关闭当前页面就会清除数据
      ② 存储的数据很小
      ③ 不参与服务器通信
    2. sessionStorage.setItem(key, value);
      
      • 1
    3. sessionStorage.getItem(key);
      
      • 1
    4. sessionStorage.removeItem(key);
      
      • 1
    5. 清空所有
      sessionStorage.clear();
      
      • 1
  • 相关阅读:
    C++二分查找算法:132 模式解法二枚举2
    CSS便捷小工具
    [论文精读|顶刊论文]Relational Triple Extraction: One Step is Enough
    subprocess Python执行系统命令最优选模块
    Kotlin注解
    【MetaGPT】单智能体多动作实践——AI小说家
    读《文明之光》第2册总结
    Elasticsearch:使用 docker compose 来实现热温冷架构的 Elasticsearch 集群
    限量版Spring实战笔记与其在收藏里吃灰,不如大家一起学习,欸 大家一起卷!
    文件包含总结
  • 原文地址:https://blog.csdn.net/wytccc/article/details/127708127