用对象从数组中取出特定值

Taking out specific value from array with objects

制作一个待办事项应用程序,但在删除数组中的特定值时卡住了,我做错了什么,我应该如何更正它?拼接与移位方法相同。

还有没有其他方法或数据结构可用于待办事项应用程序。

const form = document.querySelector("form");
const todoInput = document.querySelector(".todoInput");
const list = document.querySelector(".renderListHere");

const todoList = [];

form.addEventListener("submit", (event) => {
    event.preventDefault();

    const text = todoInput.value.trim();

    if (text === "") {
        console.log("enter something");
    } else {
        addTodo(text);
        todoInput.value = "";
    }
});

const addTodo = (text) => {
    const todo = {
        id: Date.now(),
        text,
    };

    todoList.push(todo);
    renderTodo(todo);
};

const renderTodo = ({ text, id }) => {
    const li = document.createElement("li");

    li.classList.add("todoListItems");

    li.innerHTML = `
    <span> ${text} </span>
    <button id="${id}" class="del-btn"> x
    </button>
        `;

    list.append(li);
};

list.addEventListener("click", (event) => {
    if ((event.target.className = "del-btn")) {
        const arr = todoList.filter(
            (item) => item.id === parseInt(event.target.id)
        );
         todoList.splice(arr, 1);

    }
});

我认为您误解了 filter 方法。

Array.filter()函数returns一个新数组,所以在你的情况下,你可以使用:

todoList = todoList.filter(
   (item) => item.id !== parseInt(event.target.id)
);

因此,您仅使用 ID 不同于 event.target.id 的项目过滤 todoList,并将结果应用于相同的 todoList 变量。

 const arr = todoList.filter(
        (item) => item.id !== parseInt(event.target.id)
    );
     
}

其return新数组

你不需要 splice()