繁体   English   中英

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

[英]Remove item[i] from jQuery each loop

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

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

在这种情况下,最好不要使用$.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
});

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

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

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

如果要从数组中删除元素,请使用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现在包含['a','c','d']

解决方案如下:

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

就像是

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

正如上面的@lonesomday所提到的(我根本无法在注释中添加它) grep用于数组,但你可以在grep插入你的选择器:

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

这将存储使用$(".myselector")在“茎$(".myselector")找到的所有元素,在第6个位置省略该项(列表为0索引,这使得“5”成为第6个元素)

虽然我通常更喜欢使用$.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
});

警告:这是一个新问题! 一旦项目从数组中拼接,jQuery仍将循环显示原始数组的长度。 例如:

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

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

将输出:

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

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

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)将项目推送到另一个阵列

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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM