Web Storage API会话存储:删除XYZ等所有键

时间:2017-08-21 07:53:07

标签: javascript html5 session-storage

给出以下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

有没有办法在会话存储上执行类似/通配符类型删除?

1 个答案:

答案 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?