【发布时间】:2019-07-02 17:05:57
【问题描述】:
有没有办法更改本地存储中的密钥? 例如,如果我将键设置为“4”,值设置为“myvalue”,并且我想将键更改为 3。流程会是什么?
我是不是必须先 getItem,然后是索引为 1 的 Setitem?
我想在页面卸载时调用一个函数,重新排序键并将 3 设置为 2(重新索引它)。
想法将不胜感激
【问题讨论】:
-
你要交换它们还是简单地替换2并删除3?
有没有办法更改本地存储中的密钥? 例如,如果我将键设置为“4”,值设置为“myvalue”,并且我想将键更改为 3。流程会是什么?
我是不是必须先 getItem,然后是索引为 1 的 Setitem?
我想在页面卸载时调用一个函数,重新排序键并将 3 设置为 2(重新索引它)。
想法将不胜感激
【问题讨论】:
您必须先设置新值,然后再删除旧值。像这样:
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
【讨论】:
一般做法:
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);
}
【讨论】: