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

时间:2019-02-08 12:40:09

标签: javascript local-storage

是否可以更改本地存储中的密钥? 例如,如果我将密钥设置为“ 4”,并将值设置为“ myvalue”,而我想将密钥更改为3,那么过程将如何?

我必须先获取Item,然后再使用索引为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(为其重新编制索引)。

想法将不胜感激

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

一般方法:

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);
 }