Remove item[i] from jQuery each loop

后端 未结 7 2004
别跟我提以往
别跟我提以往 2020-12-15 03:05

How do I remove an item[i] from items once it reaches in:

$.each(items, function(i) {
    // how to remove this from items
});
7条回答
  •  我在风中等你
    2020-12-15 03:54

    It would be better not to use $.each in this case. Use $.grep instead. This loops through an array in pretty much the same way as $.each with one exception. If you return true from the callback, the element is retained. Otherwise, it is removed from the array.

    Your code should look something like this:

    items = $.grep(items, function (el, i) {
        if (i === 5) { // or whatever
            return false;
        }
    
        // do your normal code on el
    
        return true; // keep the element in the array
    });
    

    One more note: this in the context of a $.grep callback is set to window, not to the array element.

提交回复
热议问题