Remove item[i] from jQuery each loop

后端 未结 7 1936
别跟我提以往
别跟我提以往 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:35

    As mentioned by @lonesomday above (I simply couldn't add this in a comment) grep is for Arrays, but you could insert your selector inside grep:

    var items = $.grep($(".myselector", function (el, i) {
      return (i===5) ? false : true;
    };
    

    This would store all elements found using $(".myselector")in ìtems` leaving out the item at the 6th position (the list is 0 indexed, which makes "5" the 6th element)

    0 讨论(0)
  • 2020-12-15 03:36

    Something like

    var indexToBeRemoved = 3; // just an illustration
    $.each(items, function(i) {
        if(i==indexToBeRemoved){
            $(this).remove();
        }
    });
    
    0 讨论(0)
  • 2020-12-15 03:40

    the solution is below:

    _.each(data, function (item, queue) {
        if (somecondition) {
            delete data[queue]
        }
    });
    
    0 讨论(0)
  • 2020-12-15 03:43

    If you want to remove an element from array, use splice()

    var myArray =['a','b','c','d'];
    var indexToRemove = 1;
    // first argument below is the index to remove at, 
    //second argument is num of elements to remove
    myArray.splice(indexToRemove , 1);
    

    myArray will now contain ['a','c','d']

    0 讨论(0)
  • 2020-12-15 03:46

    I'm guessing you want $.map. You can return null to remove an item, and not worry about how indices might shift:

    items = $.map(items, function (item, index) {
        if (index < 10) return null; // Removes the first 10 elements;
        return item;
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题