User Guide

Indexed arrays 229
Third, if you call the constructor and pass a list of elements as parameters, an array is created
with elements corresponding to each of the parameters. The following code passes three
arguments to the Array constructor:
var names:Array = new Array("John", "Jane", "David");
trace(names.length); // output: 3
trace(names[0]); // output: John
trace(names[1]); // output: Jane
trace(names[2]); // output: David
You can also create arrays with array literals or object literals. An array literal can be assigned
directly to an array variable, as shown in the following example:
var names:Array = ["John", "Jane", "David"];
Inserting array elements
Three of the Array class methods—push(), unshift(), and splice()—allow you to insert
elements into an array. The
push() method appends one or more elements to the end of an
array. In other words, the last element inserted into the array using the
push() method will
have the highest index number. The
unshift() method inserts one or more elements at the
beginning of an array, which is always at index number 0. The
splice() method will insert
any number of items at a specified index in the array.
The following example demonstrates all three methods. An array named
planets is created to
store the names of the planets in order of proximity to the Sun. First, the
push() method is
called to add the initial item,
Mars. Second, the unshift() method is called to insert the item
that belongs at the front of the array,
Mercury. Finally, the splice() method is called to
insert the items
Venus and Earth after Mercury, but before Mars. The first argument sent to
splice(), the integer 1, directs the insertion to begin at index 1. The second argument sent
to
splice(), the integer 0, indicates that no items should be deleted. Finally, the third and
fourth arguments sent to
splice(), Venus and Earth, are the items to be inserted.
var planets:Array = new Array();
planets.push("Mars"); // array contents: Mars
planets.unshift("Mercury"); // array contents: Mercury,Mars
planets.splice(1, 0, "Venus", "Earth");
trace(planets); // array contents: Mercury,Venus,Earth,Mars
The push() and unshift() methods both return an unsigned integer that represents the
length of the modified array. The
splice() method returns an empty array when used to
insert elements, which may seem strange, but makes more sense in light of the
splice()
method’s versatility. You can use the
splice() method not only to insert elements into an
array, but also to remove elements from an array. When used to remove elements, the
splice() method returns an array containing the elements removed.