【JS】localStorage用法

参考资料

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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值