Recipe 5.1. Adding
Elements to the Start or End of an Array
Problem
You want
to add elements to an
existing array.
Solution
Use the
push( ) method to append elements to the end of an array;
use the unshift( )
method to insert elements at the beginning of an array.
Discussion
You append elements to the end of an existing
array using the
Array.push( ) method, passing it one or more values to be
appended:
var array:Array = new Array();
array.push("val 1", "val 2");
You can also append a single element by using
the array's length property as the index. Because
ActionScript array indexes
are zero-indexed (meaning
that the first index is 0, not 1), the last element is at an index
of Array .length - 1. Therefore, putting
an element at index Array .length creates
a new element right after the current last element; for
example:
array[array.length] = "val 3";
If you set an element with an index that doesn't
exist, the array extends itself to include the necessary number of
elements automatically. If there are any intervening elements, they
are initialized to undefined. For example,
letters will contain the elements ["a", "b", "c",
undefined, undefined, "f"] after you execute the following
statements:
var letters:Array = ["a", "b", "c"];
letters[5] = "f";
Appending elements onto an array is common when
you want to build an array incrementally or when you want to store
the history of a user's actions for the purpose of implementing a
back button or history feature.
To add elements to the beginning of an array,
use the unshift( ) method. This shifts the existing elements
up by one index position, and inserts the new element at index
0:
// Create an array with four elements:
// "a", "b", "c", and "d".
var letters:Array = new Array( );
letters.push("a", "b", "c", "d");
// Add "z" to the beginning of the array. This shifts all
// the other elements so the value of "a" moves from
// index 0 to index 1, etc.
letters.unshift("z");
// Display the results by looping through the elements.
// See Recipe 5.2.
for (var i:int = 0; i < letters.length; i++) {
trace(letters[i]);
}
Should you add elements to the beginning or the
end of an array? That generally depends on how you intend to access
or remove the elements at a later time. For example, if you want to
access items in last in, first out (LIFO) order, you
might use Array.push( ) to add elements to an array and Array.pop( ) to remove the
elements in reverse order.
See Also
Recipe
5.2
|