Java Script Arrays
Java Script Arrays
17
Arrays:
Removing, inserting,
and extracting elements
Use the shift method to remove an element from the beginning of an
array.
Suppose you have an array, pets, whose elements are "dog", "cat",
and "bird". The
following removes the first element, "dog", leaving you with a two-
element array.
pets.shift();
To add one or more elements to the beginning of an array, use the
unshift method. The
following code adds two elements to the beginning of the array.
pets.unshift("fish", "ferret");
Use the splice method to insert one or more elements anywhere in
an array, while
optionally removing one or more elements that come after it.
Suppose you have an array with
the elements "dog", "cat", "fly", "bug", "ox". The following code adds
"pig", "duck", and "emu"
after "cat" while removing "fly" and "bug".
pets.splice(2, 2, "pig", "duck", "emu");
The first digit inside the parentheses is the index of the position
where you want to start
adding if you're adding and deleting if you're deleting. The second
digit is the number of
existing elements to remove, starting with the first element that
comes after the element(s) that
you're splicing in. The code above leaves you with an array
consisting of "dog", "cat", "pig",
"duck", "emu", and "ox".
You could make additions without removing any elements. The
following code adds
"pig", "duck", and "emu" without removing any elements.
pets.splice(2, 0, "pig", "duck", "emu");
You can also remove elements without adding any. If you start with
the elements "dog",
"cat", "fly", "bug", and "ox", the following code removes two
elements starting at index 3
—"bug" and "ox". This leaves "dog", "cat", and "fly".
pets.splice(2, 2);
Use the slice method to copy one or more consecutive elements in
any position and put
them into a new array. If you start with an array, pets, consisting of
"dog", "cat", "fly", "bug",
57
and "ox", the following code copies "fly" and "bug" to the new array
noPets and leaves the
original array, pets, unchanged.
var noPets = pets.slice(2, 4);
The first digit inside the parentheses is the index of the first element
to be copied. The
second digit is the index of the element after the last element to be
copied.
Two things could trip you up here:
Since the first index number inside the parentheses specifies the
first element to be
copied, you might think the second index number specifies the last
element to be copied.
In fact, the second number specifies the index number of the
element after the last element
to be copied.
You must assign the sliced elements to an array. It could, of course,
be the same array
from which you're doing the slicing. In that case, you'd be reducing
the original array to
only the copied elements.