简体   繁体   中英

I can't remove an item from an array

This is what I found online on how to remove an item from an array. I use splice, but when I open the console it says undefined. How can I remove the item from the array with jquery or javascript?

Thanks.

var images;

    function readURL2(input, where) {
        images = input;
        var counter = 0;
        var html = "";
        if (input.files && input.files[0]) {
            for (var i = 0; i < input.files.length; i++) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    html += "<tr><td><img src='" + e.target.result + "' height='100'></td><td><button type='button' class='btn btn-danger' onclick='removeImg(" + counter + ")'><span class='fa fa-remove'></span> Remove</button></rd></tr>";

                    $(where).html(html);
                    counter++;
                }

                reader.readAsDataURL(input.files[i]);
            }
        }
    }

    function removeImg(imgIndex) {
        images.files.splice(imgIndex, 1);
        console.log(images.files);
        readURL2(images, "#miltiim");
    }

// Start with an initial array

var array = ["a", "b", "c"];

// Find and remove item from an array

var i = array.indexOf("b");
if(i != -1) {
    array.splice(i, 1);
}

Of course if you'd like to remove multiple occurrences of the same string/number, you'll need add a bit more logic:

for(var i = array.length-1; i--;){
    if (array[i] === "b") array.splice(i, 1);
}

You may be thinking that the filter method would work...

array.filter(function(i) {
    return i != "b"
});

...but that will return a new array, thus not modifying the original.

Removing a given value from an array isn't too difficult of a task when you have a reliable snippet nearby!

-

source : http://davidwalsh.name/remove-item-array-javascript

The problem is that you supply the initial index of each image to the remove function, but removing an image changes the index within the images array:

Initial:
         index
image0   0
image1   1
image2   2

removeImg("1") will remove image1, you will have:

         index
image0   0
image2   1

removeImg("2") to remove image2 will not work as its index now is 1.

What you should do, and will not require to generate the images each time, is to set an id for each tr containing an image and remove it using jquery:

Html:

<tr id='row-image-"+counter+"'>
<td>
<img src='" + e.target.result + "' height='100'>
</td>
<td>
<button type='button' class='btn btn-danger'
        onclick='removeImg(" + counter + ")'>
<span class='fa fa-remove'></span> Remove</button>
</rd>
</tr>

JS:

function removeImg(imgIndex) {
    $('#row-image-'+imgIndex).remove();
}

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