localStorage使用总结

原创 448894534 随笔 JavaScript 154阅读 2017-11-13 16:38:56 举报

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
</style>
</head>
<body>
</body>
<script type="text/javascript">
if(!window.localStorage){
alert("浏览器不支持localstorage");
}else{
var storage=window.localStorage;
//写入a字段
storage["a"]=0;
//写入b字段
storage.b=1;
//写入c字段
storage.setItem("c",2);
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);
// localStorage的更改
storage.a=3;
console.log(storage.a);
// localStorage的删除
// storage.clear();//所有内容清除
// console.log(storage);
// storage.removeItem("a");//某个键值对删除
// console.log(storage.a);
// localStorage的键获取

    //遍历并输出localStorage里存储的名字和值
    for(var i=0; i<localStorage.length;i++){
        console.log('localStorage里存储的第'+i+'条数据的名字为:'+localStorage.key(i)+',值为:'+localStorage.getItem(localStorage.key(i)));
    }

// 将数组转为本地字符串
var arr = ['aa','bb','cc']; // ["aa","bb","cc"]
localStorage.arr = arr;//["aa","bb","cc"]
localStorage.arr.toLocaleString(); // "aa,bb,cc"

    var data={
        name:'xiecanyong',
        sex:'man',
        hobby:'program'
    };
    var d=JSON.stringify(data);
    storage.setItem("data",d);
    console.log(storage.data);
    //将JSON字符串转换成为JSON对象输出

// var json=storage.getItem("data");
// var jsonObj=JSON.parse(json);
// console.log(typeof jsonObj);
}

// ie8以上才支持localStorage
var arrDisplay = [0, 1, 1, 1];
//存储,IE6~7 cookie 其他浏览器HTML5本地存储
if (window.localStorage) {
localStorage.setItem("menuTitle", arrDisplay);
} else {
cookie.write("menuTitle", arrDisplay);
}
// 当我们每次load页面的时候,就要将相对应的数据读出来。如下:
var strStoreDate = window.localStorage? localStorage.getItem("menuTitle"): cookie.read("menuTitle");
console.log(strStoreDate)
</script>
</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复