Javascript 每次循环从 jQuery 中删除 item[i]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4869292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:30:39  来源:igfitidea点击:

Remove item[i] from jQuery each loop

javascriptjquery

提问by bcm

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

一旦它到达,我如何从项目中删除项目[i]:

$.each(items, function(i) {
    // how to remove this from items
});

采纳答案by leeny

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

如果要从数组中删除元素,请使用 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);

myArraywill now contain ['a','c','d']

myArray现在将包含 ['a','c','d']

回答by lonesomeday

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

$.each在这种情况下最好不要使用。使用$.grep来代替。这以$.each与一个例外几乎相同的方式遍历数组。如果true从回调返回,则保留该元素。否则,它将从数组中删除。

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: thisin the context of a $.grepcallback is set to window, not to the array element.

还有一点要注意:this$.grep回调的上下文中设置为window,而不是数组元素。

回答by David Tang

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

我猜你想$.map。您可以return null删除一个项目,而不必担心索引可能会如何变化:

items = $.map(items, function (item, index) {
    if (index < 10) return null; // Removes the first 10 elements;
    return item;
});

回答by Evren Kutar

the solution is below:

解决方案如下:

_.each(data, function (item, queue) {
    if (somecondition) {
        delete data[queue]
    }
});

回答by Aliostad

Something like

就像是

var indexToBeRemoved = 3; // just an illustration
$.each(items, function(i) {
    if(i==indexToBeRemoved){
        $(this).remove();
    }
});

回答by Netsi1964

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

正如上面@lonesomday 所提到的(我根本无法在评论中添加它)grep适用于数组,但您可以将选择器插入其中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)

这将存储$(".myselector")在 ìtems` 中找到的所有元素,将第 6 个位置的项目排除在外(列表的索引为 0,这使得“5”成为第 6 个元素)

回答by KMJungersen

Although I would typically prefer using $.grep()to filter the array, I have an instance where I'm already using $.each()on the array to process a dataset. After doing some processing, I can determine whether or not the item needs to be removed from the array:

虽然我通常更喜欢使用$.grep()过滤数组,但我有一个实例,我已经$.each()在数组上使用它来处理数据集。做一些处理后,我可以确定是否需要从数组中删除该项目:

// WARNING - DON'T DO THIS:
$.each(someArray, function(index, item) {
    // Some logic here, using 'item'

    if (removeItem) {
        // Spice this item from the array
        someArray.splice(index, 1)
    }

    // More logic here
});

WARNING:This presents a new problem! Once the item has been spliced from the array, jQuery will still loop for the length of the original array. E.g.:

警告:这提出了一个新问题!一旦项目从数组中拼接出来,jQuery 仍然会循环原始数组的长度。例如:

var foo = [1,2,3,4,5];

$.each(foo, function(i, item) {
    console.log(i + ' -- ' + item);
    if (i == 3){ 
        foo.splice(i, 1); 
    }
});

Will output:

将输出:

0 -- 1
1 -- 2
2 -- 3
3 -- 4
4 -- undefined

And foo is now [1, 2, 3, 5]. Every item in the array is "shifted" relative to the jQuery loop, and we missed the element "5" altogether, and the last item in the loop is undefined. The bestway to solve this is to use a reverse forloop (going from arr.length - 1to 0). This will ensure that removing an element won't affect the next item in the loop. However since the question here is with respect to $.each, there are a few alternative ways of solving this:

而 foo 现在是[1, 2, 3, 5]. 数组中的每一项都相对于 jQuery 循环“移位”,我们完全错过了元素“5”,循环中的最后一项是undefined. 解决此问题的最佳方法是使用反向for循环(从arr.length - 10)。这将确保删除元素不会影响循环中的下一项。但是,由于这里的问题与 $.each 相关,因此有几种替代方法可以解决此问题:

1) $.grep()the array before looping

1)$.grep()循环前的数组

var someArray = $.grep(someArray, function(item) {
    // Some logic here, using 'item'

    return removeItem == false;
});

$.each(someArray, function(index, item) {
    // More logic here
});

2) Push items into another array

2)将项目推入另一个数组

var choiceArray = [ ];

$.each(someArray, function(index, item) {
    // Some logic here, using 'item'

    if (removeItem) {
        // break out of this iteration and continue
        return true; 
    }

    // More logic here

    // Push good items into the new array
    choiceArray.push(item);
});