如何将字符串附加到会话存储键?

时间:2019-05-10 11:06:10

标签: javascript session

我想将字符串附加到我在下面的代码中尝试过的会话存储中的键上,但是不起作用

var setSession = window.sessionStorage.setItem.bind(window.sessionStorage);

window.onload = function()
{
  window.sessionStorage.setItem = function(key, value) {
            var newKey = "1234"+"::"+key;
            alert("inside account new key "+newKey);

            return setSession(newKey, value);
        }

}

任何建议都值得赞赏...

2 个答案:

答案 0 :(得分:2)

不确定使用localStoragesessionStorage会得到什么,但是这里是向key添加前缀的方法,如果前缀已经存在,请不要再次执行。此外,它还会删除原始密钥:

Object.keys(localStorage).forEach(function(key) {
  if(/^1234::/.test(key)) return; // Don't repeat if "1234::" exists already
  localStorage[`1234::${key}`] = localStorage[key];
  delete localStorage[key];
});

如果前缀1234是一个变量,那么您可以这样做:

let ID_key = '1234';

Object.keys(localStorage).forEach(function(key) {
  if(new RegExp(`^${ID_key}::`).test(key)) return; // Don't repeat if 1234 exists already
  localStorage[`${ID_key}::${key}`] = localStorage[key];
  delete localStorage[key];
});

答案 1 :(得分:1)

如果我理解正确,您想更改会话存储中某个项目的密钥吗?

您可以尝试使用下面的代码。

function changeKey(oldKey, newKey) {
    var item = sessionStorage.getItem(oldKey)
    sessionStorage.setItem(newKey, item)
    sessionStorage.removeItem(oldKey)
}

如果您想附加一个字符串,则可以改用它:

function appendToKey(oldKey) {
    var item = sessionStorage.getItem(oldKey)
    oldKey = '1234' + '::' + oldKey
    sessionStorage.setItem(newKey, item)
    sessionStorage.removeItem(oldKey)
}