如果删除了 localStorage 密钥,请将所有下一个密钥移动 1 位

If localStorage key is removed, move all next keys by 1 place

本文关键字:密钥 下一个 移动 删除 localStorage 如果      更新时间:2023-09-26

我有这种情况,我有localStorage

0,1,2,3

如果我删除键1,在我的循环中,当它到达位置时会中断1,而不是搜索下一个23等。所以我的想法是当我删除一个键时,例如键1,我希望所有下一个键向上移动一个位置。

我正在使用 Angular 1.3

for (var i = 0; i < localStorage.length; i++) {
    $scope.stored_data.push(ls.get(i));
 }

我也愿意接受这个问题的替代解决方案。只要我得到带有数据的数组,循环就不会在它们遍历数组时中断,localStorage它会做。

这是解决问题的另一种方法。不要单独存储每个值,请尝试以下操作:

//Store a list of the values as an array
var list = ["Value 1", "Value 2", "Value 3"];

//Delete the first value of the array, shifting everything forward
list.shift();
//Since local storage only supports strings, we must stringify the array
localStorage["list"] = JSON.stringify(list);
//When it's time to retrieve the list, parse it back to an array from JSON
list = JSON.parse(localStorage["list"]);