LocalStorage基础知识小结

来源:互联网 发布:职场女性知乎 编辑:程序博客网 时间:2024/06/10 01:41

cookie中每条cookie的存储空间为4k,localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。
localStorage的写入,localStorage的写入有三种方法:

if(!window.localStorage){            alert("浏览器支持localstorage");        }else{            var storage=window.localStorage;            //写入a字段            storage["a"]=1;            //写入b字段            storage.a=1;            //写入c字段            storage.setItem("c",3);            console.log(typeof storage["a"]);            console.log(typeof storage["b"]);            console.log(typeof storage["c"]);            //第一种方法读取            var a=storage.a;            console.log(a);            //第二种方法读取            var b=storage["b"];            console.log(b);            //第三种方法读取            var c=storage.getItem("c");            console.log(c);      }
官方推荐的是getItem\setItem这两种方法对其进行存取.localStorage只支持string类型的存储.

localStorage的删除

storage.clear();   // 删除所有内容storage.removeItem("a");  // 删除某个键对应的值