参考资料
https://developer.mozilla.org/zh-CN/docs/Web/API/Storage/LocalStorage
https://www.jianshu.com/p/3657491c0102
https://blog.csdn.net/sleepwalker_1992/article/details/82832123
https://www.cnblogs.com/xiaoniaohhl/p/11206927.html
干货
window.localStorage.setItem(key, value);
window.localStorage.getItem(key);
window.localStorage.removeItem(key);
// 获取指定索引的key
window.localStorage.key(i);
window.localStorage.length;
实现(针对object类型)
/**
* 将object类型存入local storage
*/
function saveToLocalStorage() {
var data = {};
data.name = "NAME";
data.age = 3;
data.mailAddress = "NAME@123.com";
var key = data.name;
window.localStorage.setItem(key, JSON.stringify(data));
// 最多保留10条
deleteLocalStorageOverrange();
}
/**
* 删除过期内容
*/
function deleteLocalStorageOverrange() {
// 读取时一定要进行排序
var values = getLocalStorageAllValues();
var storage = window.localStorage;
var length = values.length;
for (var i = 0; i < length - 10; i++) {
var key = values[i].name;
storage.removeItem(key);
}
}
/**
* 读取local storage全部key
*/
function getLocalStorageAllKeys() {
var keys = [];
var storage = window.localStorage;
var length = storage.length;
for (var i = 0; i < length; i++) {
keys.push(storage.key(i));
}
keys.sort();
return keys;
}
/**
* 读取local storage所有值(object类型)并排序
*/
function getLocalStorageAllValues() {
var values = [];
var storage = window.localStorage;
var length = storage.length;
for (var i = 0; i < length; i++) {
values.push(JSON.parse(storage.getItem(storage.key(i))));
}
values.sort(function (a, b) {
return (a.createTime - b.createTime);
});
return values;
}