Recipe 6.1 Adding Elements to the Start or End of an Array

6.1.1 Problem

You want to add elements to an existing array.

6.1.2 Solution

Use the push( ) method to append elements to an array; use the unshift( ) method to insert elements at the beginning of an array.

6.1.3 Discussion

You can append elements to an existing array using the Array.push( ) method, passing it one or more values to be appended:

myArray = new Array(  );
myArray.push("val 1", "val 2");

You can also append a single element using the array's length property as the index. Because ActionScript array indexes are zero-relative (meaning that the first index is 0, not 1), the last element is at an index of Array.length - 1.

myArray[myArray.length] = "val 3";

If you try to set an element with an index that does not yet exist, the array is extended to include the necessary number of elements automatically (in which case intervening elements are initialized to undefined). For example, after executing the following statements, myArray contains the elements ["a", "b", "c", undefined, undefined, "f"]:

myArray = ["a", "b", "c"];
myArray[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, which shifts the existing elements by one index position, and inserts the new element at index 0:

// Create an array with four elements: "a", "b", "c", and "d".
myArray = new Array(  );
myArray.push("a", "b", "c", "d");

// Add "z" to the beginning of the array. This shifts all the other elements so that
// the value "a" moves from index 0 to index 1, etc.

// Display the results by looping through the elements. See Recipe 6.2.
for (var i = 0; i < myArray.length; i++) {

Should you add elements to the beginning or the end of an array? That depends on your goal. It also 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.

    Part I: Local Recipes
    Part II: Remote Recipes