有没有办法更改本地存储中的密钥名称。例如:

is there a way to change key name in local storage. for example:

我想删除键名为“1”的项目

key item
"0" "first item"
"1" "second item"
"2" "third item"
"3" "fourth item"

当我删除它时它看起来像这样

key item
"0" "first item"
"2" "third item"
"3" "fourth item"

我希望它在我删除后像这样

key item
"0" "first item"
"1" "third item"
"2" "fourth item"

我知道您不能更改密钥名称,但您可以使用不同的密钥名称和相同的项目密钥设置新的密钥项目对。然后删除之前的键值对。

请帮帮我。我想不通。我已经试了两天了

我知道我在这里走投无路,但我试试运气并假设,您实际上想做的是维护一个项目列表并保持它在 localStorage .

localStorage 中实际存储一个数组没有问题,只要它是一个字符串 - 并且要将数组转换为字符串(并能够稍后解析它),您可以使用 JSON.stringify(和 JSON.parse 取回)

localStorage

中维护一个列表
function addNewItem (item) {

  let myList = JSON.parse(localStorage.getItem("myList", "[]"));
  myList.push(item);
  localStorage.setItem("myList", JSON.stringify(myList));

}

function removeItem (index) {
 
  let myList = JSON.parse(localStorage.getItem("myList", "[]"));
  myList.splice(index, 1);
  localStorage.setItem("myList", JSON.stringify(myList));

}