I am trying to add edited task to local storage. I don't know how to replace an element in the array with new element.
I have tried to iterate through an array and if an element in the array is not equal to value of input(task) it will delete by the splice method and push a new element, but the problem is that push method adds an element to the end of the array.
function editToLocal(todo) {
let todos;
if (localStorage.getItem("todos") === null) {
todos = [];
}
else {
todos = JSON.parse(localStorage.getItem("todos"));
}
const todoIndex = todo.indexOf(todo.value);
const todosIndex = todos.index0f(todoIndex);
todos.forEach((item) => {
if (item !== todo) {
todos.splice(todosIndex, 1);
todos.push(todo);
}
});
}
the splice method allows you to also add one or more elements to the array.
So for example you can do:
let todos = ['job 1', 'job 2', 'job 3', 'job 4']; console.log(todos); todos.splice(1, 1, 'job a'); console.log(todos);
have you tried with:
let tasks = ["task1", "task2", "task3"]; const taskToReplaceIndex = tasks.indexOf("theTaskToBeReplaced") tasks = tasks.map((task, index) => { if(index === taskToReplaceIndex) return "someNewTask" return task })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.