Splice() 方法移除不在索引处的数组末尾

Splice() method removes end of array not at index

我的功能 removeItems() 是从 li 元素内的列表项中删除项。目前我可以从视图中删除该项目,但数组拼接方法从数组末尾而不是索引处删除元素。

我的代码是:

var data = [
    "Tuesday ",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday", 
    "Sunday"
];

function itemArray(ele) {
    let items = ''; 
    for (let i = 0; i < ele.length; i++) {
        items += `<li>${ele[i]} <button type='button' class='removeItem'>Remove Item</button> </li>`;
    }
    return items;
}

function addItemFunction () {
    const addButton = document.getElementById('addButton');
    const input = document.getElementById('input').value;
    data.push(input);    
    htmlInside(data);  
}

function removeItemFunction() {
    data.pop(data);    
    htmlInside(data);
}

function removeItems() {
    const listUl = main.querySelector('ul');
    listUl.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);
          var index = data.indexOf(data);
          data.splice(index, 1);
          console.log(data);
        }
      });
}

function htmlInside(data) {
        let getHtml = `
    <ul class="listItems">
        ${itemArray(data)}
        
    </ul>
    <input type='input' id='input' required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
    
    `
    document.querySelector('.hero').innerHTML = getHtml;

    addButton.addEventListener('click', function () {
        addItemFunction();
    });

    removeButton.addEventListener('click', function () {
        removeItemFunction();
    });

    removeItems();

 }  

我认为我没有正确找到数据索引。 var index = data.indexOf(this); data.splice(index, 1);

可能是个问题

当我 console.log(index) 它的日志 -1.

问题出在这一行 var index = data.indexOf(data) 您正在检查数据的索引,您应该检查数据数组中元素的索引,因此您应该首先从列表中获取该元素,例如ele=li.textContent 然后传递给 data.indexOf(ele)

在点击事件监听器中,console.logdata.splice(index, 1)返回的值。你应该看到的是-1。现在,如果您将 -1 放入拼接中,它会从末尾向后开始,在这种情况下是最后一个元素并将其删除。

这是因为.indexOf方法returns -1 when nothing' found,这里就是这种情况。