localStorage与cookie的作用类似,只能存储字符串,以键值对的方式进行存储;与cookie不同的是,可以存储更多的数据。
localStorage用于持久化的本地存储。
var skey = "StorageKey";
var svalue = "StorageValue";
1.存储键值对:
(1)window.localStorage.setItem(skey,svalue);
(2)window.localStorage.StorageKey = svalue;
(3)window.localStorage[skey] = svalue;
2.通过键获取值:
(1)svalue = window.localStorage.getItem(skey);
(2)svalue = window.localStorage.StorageKey;
(2)svalue = window.localStorage[skey];
3.同时获取localStorage中存储的键和值:
var allStorage = []; //存储全部键值对的数组
for(var i=0;i
var oneStorage = {}; //存储一个键值对的对象
oneStorage.skey = window.localStorage.key(i); //获得一个localStorage的键
oneStorage.svalue = window.localStorage.getItem(oneStorage.skey); //获得对应的值
allStorage.push(oneStorage);
}
return allStorage;
4.根据键删除值(根据键将值置空):
window.localStorage.setItem(key,"");
等其他类似存储键值对的方法
5.根据键删除键值对:
window.localStroage.removeItem(skey);
6.清空localStorage:
window.localStorage.clear();