gpt4 book ai didi

javascript - 删除条目后重新排序本地存储

转载 作者:行者123 更新时间:2023-11-28 17:10:22 25 4
gpt4 key购买 nike

有没有办法更改本地存储中的 key ?例如,如果我将键设置为“4”且值设置为“myvalue”,并且我想将键更改为 3。过程会怎样?

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

for instance, the user clicks a certain button and creates an indexed localstorage entry like so-

Then, he has the option to delete an entry which will leave him like so:

我想在页面卸载时调用一个函数,该函数对键重新排序并将 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

关于javascript - 删除条目后重新排序本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com