前端本地存储localStorage

1.突破cookie 4K限制,一般浏览器支持5M

2.增 删 改 查

  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    


<script type="text/javascript"> 
 window.onload=function(){  

    if(!window.localStorage){
            alert("浏览器不支持localstorage");
            return false;
        }else{
            var storage=window.localStorage;
            //写入a字段--增或改
            storage["a"]=1; 
            //写入b字段--增或改
            storage.b=1;
            //写入c字段 --增或改
            storage.setItem("c",3);
            //删除c
            storage.removeItem('c');
            //清空storage
            //storage.clear();
            //查询
            console.log('a:',storage.getItem('a'));
            storage.a;
            storage["a"];
            console.log(typeof storage["a"]);
            console.log(typeof storage["b"]);
            console.log(typeof storage["c"]);
        }
    } 
</script>
</body>

</html>
增删改查

 

3.遍历localStorage

var storage=window.localStorage;
            storage.a=1;
            storage.setItem("c",3);
            for(var i=0;i<storage.length;i++){
                var key=storage.key(i);
                console.log(key);
            }

 

4.存储为字符串

  JSON.stringify() # json对象转为json字符串

  JSON.parse() # json字符串转为json对象

posted @ 2018-07-20 17:39  富0代  阅读(132)  评论(0编辑  收藏  举报
返回
顶部