简体   繁体   中英

Splice() method removes end of array not at index

My function removeItems() is to remove items from a list item within a li element. Currently I can remove the item from the view but the array splice method removes the element from the end of the array and not at index.

my code is:

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();

 }  

I don't think I am finding the index of the data correctly. Might be an issue at var index = data.indexOf(this); data.splice(index, 1);var index = data.indexOf(this); data.splice(index, 1);

when I console.log(index) its logs -1.

The problem is in this line var index = data.indexOf(data) you are checking the index of the data,you should check the index of the element in the data array so you should first get that element from the list with something like ele=li.textContent and then pass it to data.indexOf(ele)

In the click event listener, console.log the value returned by data.splice(index, 1) . What you should see is -1. Now if you place -1 into a splice it start from the end backwards, in this case the last element and removes that.

This is because the .indexOf method returns -1 when nothings' found, which is the case here.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM