for 循环中的拼接不删除选定的索引

问题描述 投票:0回答:1

如果页面重新加载,splice 方法返回 [0]{'C'} 而不是 0:{'B'}

todos = [0:{"title":"A"}, 1:{"title":"B"}, 2:{"title":"C"}] //store todos - localStorage
deletedTodo = [0,2] // remove A & C from todos - store removed element index - localStorage
window.addEventListener("load", (e) => {
  todos = JSON.parse(localStorage.getItem("todos")) || [];
  clearTodo();
});

用于检查应从 todos 对象中删除的已删除索引的函数,然后返回更新的 todos 对象 否则返回显示Todos()

function clearTodo() {
  if (
    JSON.parse(localStorage.getItem("deletedTodo")) &&
    JSON.parse(localStorage.getItem("deletedTodo")).length > 0
  ) {
    for (
      let index = 0;
      index <= JSON.parse(localStorage.getItem("deletedTodo")).length;
      index++
    ) {
      todos.splice(JSON.parse(localStorage.getItem("deletedTodo"))[index], 1);
    }
    localStorage.setItem("todos", JSON.stringify(todos));

    localStorage.setItem("deletedTodo", JSON.stringify([]));
    deletedIndexex = [];

    return displayTodos();
  } else {
    return displayTodos();
  }
}
javascript splice todo
1个回答
0
投票

当您拼接时,您应该根据已删除项目的数量减少索引,因为数组变短了。由于数组的长度在循环期间是固定的,因此请在 var 中记住它并减少它以模拟数组长度的减少:

function clearTodo() {
  if (
    JSON.parse(localStorage.getItem("deletedTodo")) &&
    JSON.parse(localStorage.getItem("deletedTodo")).length > 0
  ) {
    for (
      let index = 0,
      len = JSON.parse(localStorage.getItem("deletedTodo")).length;
      index <= ;
      index++
    ) {
      todos.splice(JSON.parse(localStorage.getItem("deletedTodo"))[index--], 1);
      len--;
    }
    localStorage.setItem("todos", JSON.stringify(todos));

    localStorage.setItem("deletedTodo", JSON.stringify([]));
    deletedIndexex = [];

    return displayTodos();
  } else {
    return displayTodos();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.