Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 删除条目后重新排序localstorage_Javascript_Local Storage - Fatal编程技术网

Javascript 删除条目后重新排序localstorage

Javascript 删除条目后重新排序localstorage,javascript,local-storage,Javascript,Local Storage,是否有办法更改本地存储中的密钥? 例如,如果我将一个键设置为“4”,值设置为“myvalue”,我想将该键更改为3。这个过程是什么 我必须先获取Item,然后使用索引-1设置Item吗 我想在pageunload上调用一个函数,该函数对键进行重新排序,并将其设置为3到2(重新索引) 如果您有想法,我们将不胜感激。一般方法: function changeKeyforStorageItem(oldKey, newKey) { let myValue = localStorage.getI

是否有办法更改本地存储中的密钥? 例如,如果我将一个键设置为“4”,值设置为“myvalue”,我想将该键更改为3。这个过程是什么

我必须先获取Item,然后使用索引-1设置Item吗

我想在pageunload上调用一个函数,该函数对键进行重新排序,并将其设置为3到2(重新索引)

如果您有想法,我们将不胜感激。

一般方法:

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

一般做法:

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


在删除旧值之前,必须先设置新值。像这样:

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 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

有没有办法在整个本地存储中循环?也许是一个运行到存储的for循环。长度?更多关于这个。。。说得好,猫。通过本地存储进行循环也可能会变得不必要的复杂;我已经用建议的替代方法更新了我的原始答案。有没有办法在整个本地存储中循环?也许是一个运行到存储的for循环。长度?更多关于这个。。。说得好,猫。通过本地存储进行循环也可能会变得不必要的复杂;我已使用建议的替代方法更新了我的原始答案。是否要交换它们或简单替换2并删除3?是否要交换它们或简单替换2并删除3?