我有不同的本地存储,例如:
__user_information_1494653090436
__user_information_1494652962487
__user_information_1494653208375
哪里
1494653090436, 1494652962487, and 1494653208375
是不同的时间戳。
我只是想如何删除除最新时间戳之外的所有本地存储。任何帮助。
最佳答案
您的第一步需要从 localStorage 获取所有这些 key 。这可以通过 Object.keys 来完成
var allKeys = Object.keys(localStorage);
然后你只需找出哪个是最新的并删除其余的
var sorted = allKeys
// Use regex to find your keys of interest
.map(key => key.match(/__user_information_([0-9]+)/))
// Filter out those that don't match
.filter(match => !!match)
// Sort by timestamp
.sort((a, b) => {
var a_ = parseInt(a[1]), b_ = parseInt(b[1]);
return a_ > b_ ? 1
: b_ > a_ ? -1
: 0;
});
// Remove all but last
for(var i = 0; i < sorted.length - 1; i++) {
localStorage.removeItem(sorted[i][0]);
}
关于javascript - 删除本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43950149/