sessionStorage和localStorage数据存储也有大小限制,但却比cookie大得多,可以达到5M甚至更大!
localStorage:没有时间限制的数据存储!
sessionStorage:由英文意思也可知,它是对session的数据存储,所以在用户关闭浏览器(标签页/窗口)后,数据被删除!
•localStorage.setItem(key,value):设置(保存)数据;相当于localStorage.key=value!
•localStorage.getItem(key):获取数据
•localStorage.removeItem(key):删除单个数据
•localStorage.clear():删除所有数据
•localStorage.key(index):获取某个索引的键值
设置值
localStorage.name = 'xiao ming';
localStorage.setItem('name1', 'Apple');
---------------------------
var obj = { name:'Jim' };
localStorage.obj = obj;
取值
localStorage.getItem(key); //获取数据
var name = localStorage.name; //获取数据
console.log(name);
--------------------------
var obj = localStorage.getItem("obj");
var str = JSON.stringify(obj);
缓存 localStorage 存 取 array
var weekArray = ['周一','周二','周三','周四','周五']; localStorage.setItem('weekDay',JSON.stringify(weekArray)); ==================== 取 weekArray = JSON.parse(localStorage.getItem('weekDay')); console.log(weekArray.length); console.log(weekArray[5]);
var userEntity = { name: 'tom', age: 22 }; // 存储值:将对象转换为Json字符串 sessionStorage.setItem('user', JSON.stringify(userEntity)); // 取值时:把获取到的Json字符串转换回对象 var userJsonStr = sessionStorage.getItem('user'); userEntity = JSON.parse(userJsonStr);
sessionStorage.getItem('testKey'); // => 返回testKey对应的值
sessionStorage['testKey']; // => 这是一个测试的value值
站长微信:xiaomao0055
站长QQ:14496453