【浏览器系列】浏览器本地存储

简介

本文主要介绍浏览器的本地存储
概念:

  1. 浏览器的本地存储是指浏览器端通过window.sessionStorage和window.localStorage属性来进行浏览器的本地存储的。
  2. 一般能存5M左右的数据。

说白了就是八个api 的使用。

  1. 相关API:

    1. xxxxxStorage.setItem('key', 'value'); 该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。

    2. xxxxxStorage.getItem('person');

      ​ 该方法接受一个键名作为参数,返回键名对应的值。

    3. xxxxxStorage.removeItem('key');

      ​ 该方法接受一个键名作为参数,并把该键名从存储中删除。

    4. xxxxxStorage.clear()

      ​ 该方法会清空存储中的所有数据。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>浏览器本地存储</title>
</head>
<body>
    
    <script>

        //首先使用sessionStorage对象。
        //增,参数是key value
        window.sessionStorage.setItem("name","jiazulong");

        //获取
        var name = window.sessionStorage.getItem("name");
        console.log("name=",name);
    
        //改
        window.sessionStorage.setItem("name","jiajibao");

        //删除
        var name = window.sessionStorage.getItem("name");
        console.log("name=",name);

        window.sessionStorage.removeItem("name");

        var name = window.sessionStorage.getItem("name");
        console.log("name=",name);

        //清空
        window.sessionStorage.clear()

        

        //其次是localStorage,api是一模一样的
        //增,参数是key value
        window.localStorage.setItem("name","jiazulong");

        //获取
        var name = window.localStorage.getItem("name");
        console.log("name=",name);
    
        //改
        window.localStorage.setItem("name","jiajibao");

        //删除
        var name = window.localStorage.getItem("name");
        console.log("name=",name);

        window.localStorage.removeItem("name");

        var name = window.localStorage.getItem("name");
        console.log("name=",name);

        //清空
        window.localStorage.clear()

        
    </script>
</body>
</html>

效果如下:

 浏览器的本地存储可以在开发者工具中看到。
首先要先注释掉上面的代码中删除和清空的代码:

 

 

         sessionStorage和localStorage的区别是,sessionStorage会在窗口关闭重新打开后消失,而localStorage是保存在磁盘的,把浏览器关闭掉也不会消失,只有手动删除才会消失,如果获取的存储的key不存在,会返回null。

网站中的本地存储:

 总结:

  1. SessionStorage存储的内容会随着浏览器窗口关闭而消失。
  2. LocalStorage存储的内容,需要手动清除才会消失。
  3. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
  4. JSON.parse(null)的结果依然是null。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码上游

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值