Java Reference
In-Depth Information
Notice that an empty array is returned, but the new value of "Ham & Mushroom" has been
inserted, which we can see if we look at the
pizzas
array:
pizzas;
<< ["Chicken & Bacon", "Mushroom", "Chicken and Pepper",
"Veggie
↵
Deluxe", "Ham & Mushroom", "Spicy Beef", "Chicken and
Mushroom"]
We saw earlier that we can use the
delete
operator to remove an item from an array. Un-
fortunately, this leaves a value of
undefined
in its place. If you want to remove a value
completely, you can use the
splice()
method with a length of
1
and without specifying
any values to add:
pizzas.splice(2,1); // will remove the item at index 2
(i.e. the
↵
third item in the array)
<< ["Chicken and Pepper"];
The value that has been removed will be returned as an array containing that value.
If we now look at the
pizzas
array, we can see that "Chicken and Pepper" has been re-
moved completely:
pizzas;
<< ["Chicken & Bacon", "Mushroom", "Veggie Deluxe", "Ham &
Mushroom"
↵
, "Spicy Beef", "Chicken and Mushroom"]
Reverse
We can reverse the order of an array using the
reverse()
method:
pizzas.reverse();
<< ["Chicken and Mushroom", "Spicy Beef", "Ham &
Mushroom",
↵
"Veggie Deluxe", "Mushroom", "Chicken & Bacon"]
