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

bcm*_*bcm 36 javascript jquery

如何在项目到达时从项目中删除项目[i]:

$.each(items, function(i) {
    // how to remove this from items
});
Run Code Online (Sandbox Code Playgroud)

lon*_*day 117

$.each在这种情况下最好不要使用.请$.grep改用.这循环遍历一个数组,其方式$.each与一个例外完全相同.如果true从回调返回,则保留该元素.否则,它将从阵列中删除.

您的代码应如下所示:

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
});
Run Code Online (Sandbox Code Playgroud)

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

  • 我和其他方式相比,每个 (6认同)
  • 只是澄清@ user113716非常重要的评论:`$ .grep`确实_not_修改数组; 它只是返回一个数组的副本,可能没有一些(或所有)元素. (4认同)
  • 请注意其他人.el是我只是索引的元素. (2认同)

Dav*_*ang 10

我猜你想要的$.map.您可以return null删除项目,而不必担心索引可能会如何移动:

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


lee*_*eny 9

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

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

  • 问题是如何从循环中删除它. (21认同)
  • @CiprianTarta这个问题显然格格不入,因为这回答了它...但我同意.当它在任何`$ .each`循环中时,使用splice并不真正起作用,因为它会弄乱循环. (2认同)