Tri*_*hul 19 javascript html5 local-storage
我已经存储了几个键值对,其中包含使用HTML5 localstorage变量的某些加密登录信息.我为所有关键名称添加了一个唯一的前缀TM_loginname.现在我想清除所有localstorage键值对,其键以前缀TM_开头.PS:我也尝试过sessionstorage,但只有在浏览器关闭时它才会清除.
Ron*_*yHe 37
迭代时删除元素是不安全的,因此创建一个数组来保存需要删除的键.然后,遍历该数组以删除它们:
var arr = []; // Array to hold the keys
// Iterate over localStorage and insert the keys that meet the condition into arr
for (var i = 0; i < localStorage.length; i++){
if (localStorage.key(i).substring(0,3) == 'TM_') {
arr.push(localStorage.key(i));
}
}
// Iterate over arr and remove the items by key
for (var i = 0; i < arr.length; i++) {
localStorage.removeItem(arr[i]);
}
Run Code Online (Sandbox Code Playgroud)
更现代的(ES2017)解决方案如下:
Object.entries(localStorage).map(
x => x[0] # get keys
).filter(
x => x.substring(0,3)=="TM_"
).map(
x => localStorage.removeItem(x))
Run Code Online (Sandbox Code Playgroud)
使用lodash.请享用.
_.forIn(window.localStorage, (value: string, objKey: string) => {
if (true === _.startsWith(objKey, 'TM_')) {
window.localStorage.removeItem(objKey);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10196 次 |
| 最近记录: |