localStorage的设置和取值Demo

来源:互联网 发布:简单pdf解密软件 编辑:程序博客网 时间:2024/06/17 15:53

localStorage的设置和取值Demo

    /*--------------------------- 样例一    字符串的简单缓存和获取及移除    ------------------------*/    localStorage.setItem("test","详情请看控制台localStorage内容变化,此对象2s后自动移除");  //缓存内容方法    alert("确认查看缓存内容");    alert("缓存内容: "+localStorage.getItem("test")); //获取缓存内容方法    setTimeout(function(){        localStorage.removeItem("test");//移除缓存对象方法    },2000);    /*--------------------------- 样例二  字符串的简单缓存和获取及移除 -------------------------------*/    localStorage.setItem("test01","3s后可确认移除该对象");//缓存内容方法    console.log(localStorage.getItem("test01")); //获取缓存内容方法    setTimeout(function(){            alert("确定后,移除缓存对象");        localStorage.removeItem("test01");//移除缓存对象方法    },3000);    /*--------------------------- 样例二 --对象是缓存与获取 -------------------------------*/    var data = new Object(),contArray=[1,2,3,4],contArrays=["a","b","c","d"];    data.name ="canvasDraw";    data.dataArray=contArray;    data.dataArrays=contArrays;    var str = JSON.stringify(data);  //JSON.stringify()方法用于把一个对象解析成一个字符串。例:var a = {a:1,b:2};JSON.stringify(a) 后变为 "{"a":1,"b":2}"    localStorage.setItem(data.name, str);    console.log(localStorage.getItem(data.name)); //获取缓存内容方法    console.log("------------",localStorage.getItem(data.name));    console.log("------------",JSON.parse(localStorage.getItem(data.name)));  //JSON.parse()方法用于把一个字符串解析成一个对象。例:var b = "{"a":1,"b":2}";JSON.stringify(b) 后变为 {a:1,b:2}    console.log("------------",JSON.parse(localStorage.getItem(data.name)).dataArray);
原创粉丝点击