我有以下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);
    }           
}

当前回答

举两个例子:

一个例子

// 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
        }
    }
}

其他回答

试试吧

RemoveItems.forEach((i, j) => {
    OriginalItems.splice((i - j), 1);
});

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

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

为什么在.splice上浪费CPU周期?该操作必须一次又一次地执行整个循环以删除数组中的一个元素。

为什么不只是在一个循环中使用传统的2个旗帜?

Const元素= [1,5,5,3,5,2,4]; Const remove = 5 I = 0 For(令j = 0;J < elements.length;j + +) { If(元素[j] !==删除){ 元素[i] =元素[j] 我+ + } } 元素。长度= I

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

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语句中增加了一个减量。

另一个简单的方法是一次消化数组元素:

while(Auction.auctions.length){
    // From first to last...
    var auction = Auction.auctions.shift();
    // From last to first...
    var auction = Auction.auctions.pop();

    // Do stuff with auction
}