我有以下for循环,当我使用splice()删除一个项目时,我得到'seconds'是未定义的。我可以检查它是否未定义,但我觉得可能有一种更优雅的方式来做到这一点。他们的愿望是简单地删除一个项目,然后继续前进。

for (i = 0, len = Auction.auctions.length; i < len; i++) {
    auction = Auction.auctions[i];
    Auction.auctions[i]['seconds'] --;
    if (auction.seconds < 0) { 
        Auction.auctions.splice(i, 1);
    }           
}

当前回答

这是一个很常见的问题。解决方案是反向循环:

for (var i = Auction.auctions.length - 1; i >= 0; i--) {
    Auction.auctions[i].seconds--;
    if (Auction.auctions[i].seconds < 0) { 
        Auction.auctions.splice(i, 1);
    }
}

如果你把它们从末端取出来也没关系因为下标会在逆向过程中保留下来。

其他回答

下面是另一个正确使用拼接的例子。本例将从'array'中删除'attribute'。

for (var i = array.length; i--;) {
    if (array[i] === 'attribute') {
        array.splice(i, 1);
    }
}

虽然你的问题是关于从被迭代的数组中删除元素,而不是关于有效地删除元素(除了一些其他处理),但我认为如果遇到类似情况,应该重新考虑它。

这种方法的算法复杂度是O(n^2)作为拼接函数和for循环都遍历数组(在最坏的情况下,拼接函数移位数组的所有元素)。相反,您可以将所需的元素推入到新数组中,然后将该数组赋值给所需的变量(该变量刚刚被迭代)。

var newArray = [];
for (var i = 0, len = Auction.auctions.length; i < len; i++) {
    auction = Auction.auctions[i];
    auction.seconds--;
    if (!auction.seconds < 0) { 
        newArray.push(auction);
    }
}
Auction.auctions = newArray;

自ES2015以来,我们可以使用Array.prototype.filter将所有内容都放在一行中:

Auction.auctions = Auction.auctions.filter(auction => --auction.seconds >= 0);

举两个例子:

一个例子

// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
    for (var l = temp_products_images.length; l--;) {
        // 'mark' is the checkbox field
        if (temp_products_images[l].mark == true) {
            store.state.c_products.products_images.splice(l,1);         // THIS WORKS
            // this.$delete(store.state.c_products.products_images,l);  // THIS ALSO WORKS
        }
    }
}

两个例子

// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
    let l = temp_products_images.length
    while (l--)
    {
        // 'mark' is the checkbox field
        if (temp_products_images[l].mark == true) {
            store.state.c_products.products_images.splice(l,1);         // THIS WORKS
            // this.$delete(store.state.c_products.products_images,l);  // THIS ALSO WORKS
        }
    }
}

重新计算每次循环的长度,而不是一开始就重新计算,例如:

for (i = 0; i < Auction.auctions.length; i++) {
      auction = Auction.auctions[i];
      Auction.auctions[i]['seconds'] --;
      if (auction.seconds < 0) { 
          Auction.auctions.splice(i, 1);
          i--; //decrement
      }
}

这样就不会超过上界。

EDIT:在if语句中增加了一个减量。

普通的for循环对我来说更熟悉,我只需要在每次从数组中删除一个项时递减索引

//5个正确,5个错误 Var arr1 =[假,假,真,真,假,真,假,真,真,假]; //从数组中删除false For (var I = 0;I < arr1.length;我+ +){ If (arr1[i] === false){ arr1。拼接(我,1); I——;//如果item被移除,则递减索引 } } Console.log (arr1);//应该是5个true