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
Invoke push( ), unshift( ), splice( ) or concat( ) on the array
The following sections discuss these techniques in detail.
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 = "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 = "grapes"; trace(fruits); // 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.
To extend an array without assigning values to new elements,
we can simply increase the
variable, and ActionScript will add enough elements to reach that
// 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 ...