给出以下HTML会话数据:
hasSession 1
user user_abc
CosttoServe599a8e8421a80 25
runningTotal 100
Maintenance599a8e8421a80 5
BusinessEnhancements599a8e8421a80 25
BusinessEnhancements599a8e8421a94 25
Maintenance599a8e8421a94 10
FrontierInvestments599a8e8421a94 5
CosttoServe599a8e8421a86 0
FrontierInvestments599a8e8421a86 5
我试图删除包含以下内容的所有密钥:
599a8e8421a94
有没有办法在会话存储上执行类似/通配符类型删除?
答案 0 :(得分:2)
循环遍历sessionStorage
对象,检查密钥是否包含599a8e8421a94
,如果有,请将其删除:
for (var key in sessionStorage) {
if (key.indexOf('599a8e8421a94') !== -1)
sessionStorage.removeItem(key);
}
它的一个实例:
/** Define dummy data... **/
var obj = {
'no-clean': 'i will not be cleaned.',
'testing599a8e8421a94': 25,
'another_test599a8e8421a94': 'e,ndleknfew',
'599a8e8421a94somemoretesting': '2knmsdkgsdg'
};
/** Loop through our dummy data and add it to sessionStorage. **/
for (var key in obj) {
sessionStorage.setItem(key, obj[key]);
}
/** This is the part you will need, loop through sessionStorage object. **/
for (var key in sessionStorage) {
/** Check if the key contains the search string... **/
if (key.indexOf('599a8e8421a94') !== -1)
sessionStorage.removeItem(key)
}
console.log(sessionStorage)
JSFiddle - 打开控制台以查看sessionStorage
对象中的剩余键/值。
阅读材料
How to check whether a string contains a substring in JavaScript?