O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Elements to an Array

To add elements to an array, we use one of the following techniques:

  • Specify a value for a new element at an index equal to or greater than the array's length

  • Increase the array's length variable

  • Invoke push( ), unshift( ), splice( ) or concat( ) on the array

The following sections discuss these techniques in detail.

Adding New Elements Directly

To add a new element to an existing array at a specific index, we simply assign a value to that element. The following code demonstrates:

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

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

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

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

trace(fruits[12]); // Displays: undefined

If the element already exists, it will be replaced by the new value. If the element doesn't exist, it will be added.

Adding New Elements with the length Variable

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

// Create an array with three elements
var colors = ["green", "red", "blue"];
// Add 47 empty elements, numbered 3 through 49, to the array
colors.length = 50;

You can use this ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required