【问题标题】:reordering the localstorage after deletion of an entry删除条目后重新排序本地存储
【发布时间】:2019-07-02 17:05:57
【问题描述】:

有没有办法更改本地存储中的密钥? 例如,如果我将键设置为“4”,值设置为“myvalue”,并且我想将键更改为 3。流程会是什么?

我是不是必须先 getItem,然后是索引为 1 的 Setitem?

我想在页面卸载时调用一个函数,重新排序键并将 3 设置为 2(重新索引它)。

想法将不胜感激

【问题讨论】:

  • 你要交换它们还是简单地替换2并删除3?

标签: javascript local-storage


【解决方案1】:

您必须先设置新值,然后再删除旧值。像这样:

function changeKey(oldKey, newKey) {
    localStorage.setItem(newKey, localStorage.getItem(oldKey));
    localStorage.removeItem(oldKey);
}

我建议您不要将 localStorage 用作这样的数组,而是使用单个 localStorage 项来存储您的数组:

var myArray = [ { a : 1 }, { b : 2 } ];

localStorage.setItem("myArray", JSON.stringify(myArray));

那么每当你想对数组进行操作时,都可以这样操作,数组索引会自动更新:

var myArray = JSON.parse(localStorage.getItem("myArray")); // Fetching the array

myArray.splice(myIndex, 1); // Removing an item with index 'myIndex';

localStorage.setItem("myArray", JSON.stringify(myArray)); // Storing the changes

【讨论】:

  • 有没有办法遍历整个本地存储?也许是一个运行到 storage.length 的 for 循环?
  • 好点,@Cat。循环访问 localStorage 也可能是不必要的复杂;我已经用建议的替代方法更新了我的原始答案
【解决方案2】:

一般做法:

function changeKeyforStorageItem(oldKey, newKey) {
   let myValue = localStorage.getItem(oldKey);
   localStorage.removeItem(oldKey);
   localStorage.setItem(newKey, myValue);
}

或:

 function changeKeyforStorageItem(oldKey, newKey) {
    localStorage.setItem(newKey, localStorage.getItem(oldKey));
    localStorage.removeItem(oldKey);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多