当我想从localStorage
删除待办事项时
我可以从用户界面中删除,但不能从localStorage
function deleteTodoFromStorage(deletetodo){
let todos = getTodosFromStorage();
todos.forEach(function(todo,index){
console.log(todo,deletetodo,index)
if (todo === deletetodo){
todos.splice(index,1);
console.log("Test");
}
});
localStorage.setItem("todos",JSON.stringify(todos));
}
答案 0 :(得分:1)
您不应在待办事项上调用forEach并将其自身拼接在回调中(这可能会导致索引更改)。我建议您改用过滤器方法。
newTodos = todos.filter(todo => todo !== deletetodo)
localStorage.setItem("todos",JSON.stringify(newTodos))
答案 1 :(得分:0)
这将解决您的问题:
function deleteTodoFromStorage(todoToRemove) {
localStorage.setItem(
"todos",
JSON.stringify(
JSON.parse(localStorage.getItem("todos")).filter(todoItem => {
return todoItem !== todoToRemove;
})
)
);
}
deleteTodoFromStorage("buy milk"); // or anything else