简体   繁体   中英

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. 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.

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?

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.

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.splice(indexOfRemove[i],3));}

alert(inventory), alert(discardedItem);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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