gpt4 book ai didi

javascript - 达到限制时的本地存储、限制和数据过期

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:16 25 4
gpt4 key购买 nike

我尝试将对象存储在 localStorage 中,但有时我会用完空间。

当我尝试使用 localStorage 存储对象但没有足够的存储空间时 - 有没有一种方法可以根据需要简单地删除尽可能多的本地数据以释放该空间,从最古老的元素?

浏览器中是否有 API 可以让我这样做?

最佳答案

这是我刚刚提出的一个小型概念证明。它假定当您尝试存储项目但没有空间时抛出异常。

代码有注释

var Storage = function (iden) { // a storage wrapper object
var storage; // temp storage with variable
if (localStorage[iden]) { // if we already did this, reuse
storage = JSON.parse(localStorage[iden]);
} else {
// the queue is for the item order to find out oldest
storage = {
__queue: [],
items: {}
};
}

function fetch(key) {
console.log(storage);
return storage.items[key];
}

function put(key, value) {
try {
storage.__queue.push(key);
storage.items[key] = value;
localStorage[iden] = JSON.stringify(storage);
} catch (e) { // out of space
if (storage.__queue.length === 0) throw Exception("Too big anyway");
var k = storage.__queue.pop();
delete storage.items[k];
return put(key, value); //try again after deleting
}
}
return {
put: put,
fetch: fetch
};
};

关于javascript - 达到限制时的本地存储、限制和数据过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20055998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com