6.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 an array; use the unshift( ) method to insert elements at the beginning of an array.

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: ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.