Java Reference
In-Depth Information
Note that this operation is non-destructive ―no items are actually removed from the array,
as we can see if we look at the pizzas array:
pizzas;
<< ["Chicken & Bacon", "Mushroom", "Pepperoni", "Spicy
Beef",
"Chicken and Mushroom"]
The splice() method removes items from an array and then inserts new items in their
place. Say Donatello wanted to remove the Pepperoni pizza from the pile and replace it
with some other boxes containing Chicken and Pepper, and Veggie Deluxe:
> pizzas.splice(2, 1, "Chicken and Pepper", "Veggie
Deluxe")
<< ["Pepperoni"]
> pizzas
<< ["Chicken & Bacon", "Mushroom", "Chicken and Pepper",
"Veggie
Deluxe", "Spicy Beef", "Chicken and Mushroom"]
The first number tells us the index at which to start the splice. In the example we started at
index 2, which is the third item in the array ("Pepperoni"). The second number tells us how
many items to remove from the array. In the example, this was just the one item. Every
value after this is then inserted into the array at the same place the other items were re-
moved. The strings "Chicken and Pepper", "Veggie Deluxe" are inserted in our example,
starting at the third item. Notice that the splice() method returns the items removed
from the array as a subarray, so in the example, it returned the array ["Pepperoni"] .
The splice() method can also be used to insert values into an array at a specific index
without removing any items, by indicating that zero items are to be removed:
pizzas.splice(4,0,"Ham & Mushroom"); // inserts "Ham &
Mushroom as
the fifth item in the pizzas array
<< []
Search WWH ::




Custom Search