简体   繁体   English

JavaScript:同时从数组中删除三个项目。 如何跟踪所有已删除的项目?

[英]JavaScript: Removing three items from an array at the same time. How to keep track of all the removed items?

The 1st Code removes a total of four items ( "item1" , "item4" , "item8" , and "item10" ) from the inventory array. 第一个代码从inventory数组中删除了总共四个项目( "item1""item4""item8""item10" )。 They are removed one by one. 它们被一一移除。 And in the process, the code successfully keeps track of all the removed items by lining them up in the discardedItem array, courtesy of the push or unshift function. 并且在此过程中,代码通过pushunshift函数将代码排列在被discardedItem数组中,从而成功跟踪所有已删除的项目。

The 2nd Code, However, puts me in a bind. 但是,第二代码使我陷入困境。 The code tries to remove three items from an array at the same time, and this process repeats itself four times. 该代码尝试同时从一个数组中删除三个项目,并且此过程将自身重复四次。 In this case, the following command that has worked in the 1st Code does not yield successful results: 在这种情况下,在第一代码中起作用的以下命令不会产生成功的结果:

discardedItem.unshift(inventory[indexOfRemove[i]]);

How should I modify this piece of code to have all the removed items appear in the discardedItem array in the 2nd Code? 我应该如何修改这段代码,以使所有已删除的项目出现在第二代码的discardedItem数组中?

1st Code (removing one item at a time) 第一个代码 (一次删除一项)

var inventory = ['item1', 'item2', 'item3', 'item4', 'item5', 
    'item6', 'item7', 'item8', 'item9', 'item10'],

    indexOfRemove = [0, 3, 7, 9],

    discardedItem = [];


for (var i = indexOfRemove.length - 1; i >= 0; i--) {

    discardedItem.unshift(inventory[indexOfRemove[i]]);

    inventory.splice(indexOfRemove[i], 1);

}


alert(inventory), alert(discardedItem);

2nd Code (removing three items at a time) 第二代码 (一次删除三项)

var inventory = ['item1', 'item2', 'item3', 'item4', 'item5', 
    'item6', 'item7', 'item8', 'item9', 'item10'],

    indexOfRemove = [0, 3, 7, 9],

    discardedItem = [];


for (var i = indexOfRemove.length - 1; i >= 0; i--) {

    discardedItem.unshift(inventory[indexOfRemove[i]]);

    inventory.splice(indexOfRemove[i], 3);

}


alert(inventory), alert(discardedItem);

Splice returns the array of deleted elements.Add the array returned by splice to push of the discardedItem. Splice返回已删除元素的数组,将splice返回的数组添加到pushededItem中。

var inventory = ['item1', 'item2', 'item3', 'item4', 'item5', 
'item6', 'item7', 'item8', 'item9', 'item10'],
indexOfRemove = [0, 3, 7, 9],
discardedItem = [];

for (var i = indexOfRemove.length - 1; i >= 0; i--) { for(var i = indexOfRemove.length-1; i> = 0; i--){

discardedItem.unshift(inventory.splice(indexOfRemove[i],3));}

alert(inventory), alert(discardedItem); 警报(库存),警报(丢弃的物品);

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

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