User Guide
230 Working with Arrays
Removing array elements
Three methods of the Array class—pop(), shift(), and splice()—allow you to remove
elements from an array. The
pop() method removes an element from the end of the array. In
other words, it removes the element at the highest index number. The
shift() method
removes an element from the beginning of the array, which means that it always removes the
element at index number 0. The
splice() method, which can also be used to insert
elements, removes an arbitrary number of elements starting at the index number specified by
the first argument sent to the method.
The following example uses all three methods to remove elements from an array. An array
named
oceans is created to store the names of large bodies of water. Some of the names in the
array are lakes rather than oceans, so they need to be removed.
First, the
splice() method is used to remove the items Aral and Superior, and insert the
items
Atlantic and Indian. The first argument sent to splice(), the integer 2, indicates
that the operation should start with the third item in the list, which is at index 2. The second
argument, 2, indicates that two items should be removed. The remaining arguments,
Atlantic and Indian, are values to be inserted at index 2.
Second, the
pop() method is used to remove last element in the array, Huron. And third, the
shift() method is used to remove the first item in the array, Victoria.
var oceans:Array = ["Victoria", "Pacific", "Aral", "Superior", "Indian",
"Huron"];
oceans.splice(2, 2, "Arctic", "Atlantic"); // replaces Aral and Superior
oceans.pop(); // removes Huron
oceans.shift(); // removes Victoria
trace(oceans); // output: Pacific,Arctic,Atlantic,Indian
The pop() and shift() methods both return the item that was removed. The data type of
the return value is Object because arrays can hold values of any data type. The
splice()
method returns an array containing the values removed. You can change the oceans array
example so that the call to
splice() assigns the array to a new array variable, as shown in the
following example:
var lakes:Array = oceans.splice(2, 2, "Arctic", "Atlantic");
trace(lakes); // output: Aral,Superior
You may come across code that uses the delete operator on an array element. The delete
operator sets the value of an array element to
undefined, but it does not remove the element
from the array. For example, the following code uses the
delete operator on the third
element in the
oceans array, but the length of the array remains 5:
var oceans:Array = ["Arctic", "Pacific", "Victoria", "Indian", "Atlantic"];
delete oceans[2];
trace(oceans); // output: Arctic,Pacific,,Indian,Atlantic