localStorage 不保存相似名称的值

localStorage is not saving values of similar names

我的 localStorage 只保存了几个相似名称的变量 (3),然后继续用新值覆盖最后一个变量。

我想做的是将变量添加到 localStorage 中,这些变量具有名称和附加的数字,例如 Test1Test2 Test3、等等

唯一的问题是在第三个元素之后,在本例中为 Test3,键被覆盖为 Test4 并且值发生变化到新的价值。只要单词 Test 相同,这种情况就会永远发生。

我可以添加其他值,但最多只能添加 3 个相同的词根。

这是我用来添加元素的代码:

const AddToLocalStorage = (type, contents) => {
    let ind = 0;
    Object.keys(localStorage).forEach(function (key) {
        if (key == (type + ind)) {
            ind++;
        } else {
            return;
        }
    });
    localStorage.setItem((type + ind), JSON.stringify(contents));
}

type是一个字符串如Test
contents是存储的值

提前致谢:)

编辑 - 你能否说明如何调用 AddToLocalStorage 函数

AddToLocalStorage("Test", "value");

localStorage 中,这将设置为 { "Test0", "value" }

首先,JavaScript 对象 属性 顺序 isn't guaranteed,因此您可能没有按照浏览器显示的顺序接收密钥


也就是说,让我们添加一些 console.log 来调试代码:

const AddToLocalStorage = (type, contents) => {
    let ind = 0;
    console.log('Existing keys', Object.keys(localStorage));
    Object.keys(localStorage).forEach(function (key) {
        if (key == (type + ind)) {
            ind++;
        } else {
            return;
        }
    });
    console.log('Set', (type + ind))
    localStorage.setItem((type + ind), JSON.stringify(contents));
}
AddToLocalStorage("Test", "value1");

在第二个 运行 上,记录:

Existing keys (3) ["Test2", "Test0", "Test1"]
Set Test2

在这里我们可以看到 (type + ind) 将是 Test2,因为对于 Test1Test2(key == (type + ind)) 将是 true

由于 Test2 已经存在,您将覆盖现有值。