Adding Elements to an Array

You can add elements to an array by specifying a value for a new element, increasing the array’s length property, or using one of the built-in array functions.

Adding New Elements Directly

We can add a new element to an existing array at a specific index by simply assigning a value to that element:

// Create an array, and assign it three values
var myList = ["apples", "oranges", "pears"];

// Add a fourth value
myList[3] = "tangerines";

The new element does not need to be placed immediately after the last element of the old array. If we place the new element more than one element beyond the end of the array, ActionScript automatically creates empty elements for the intervening indexes:

// Leave indexes 4 to 38 empty
myList[39] = "grapes";

trace (myList[12]); // Display is empty because element 12 is undefined

Adding New Elements with the length Property

To extend an array without assigning values to new elements, we can simply increase the length property and ActionScript will add enough elements to reach that length:

// Create an array with three elements
var myColors = ["green", "red", "blue"];

// Add 47 empty elements, numbered 3 through 49, to the array
myColors.length = 50;

You might use this approach to create a number of empty elements to hold some data you expect to accumulate, such as student test scores.

Adding New Elements with Array Methods

We can use built-in array methods to handle more complex element-addition scenarios. (We’ll learn in Chapter 12 ...

Get ActionScript: The Definitive Guide 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.