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.
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
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.
We can use built-in array methods to handle more complex element-addition scenarios. (We'll learn in Chapter 12, "Objects and Classes", that a method is a function that operates on an object.)
The push( ) method appends one or more elements to the end of an array. It automatically appends the data after the last element of the array, so we don't need to worry about how many elements already exist. The push( ) method can also append multiple elements to an array at once. To invoke push( ) on an array, we use the array name followed by the dot operator, by the keyword push, and zero or more parameters in parentheses:
arrayName.push(item1, item2,...itemn);
where item1, item2,...itemn are a comma-separated list of items to be appended to the end of the array as new elements. Here are some examples:
// Create an array with two elements var menuItems = ["home", "quit"]; // Add an element // menuItems becomes ["home", "quit", "products"] menuItems.push("products"); // Add two more elements // menuItems becomes ["home", "quit", "products", "services", "contact"] menuItems.push("services", "contact");
When invoked with no arguments, push( ) appends an empty element:
menuItems.push( ); // Increase array length by one // Same as menuItems.length++;
The push( ) method returns the new length of the updated array:
var myList = [12, 23, 98]; trace(myList.push(28, 36)); // Appends 28 and 36 to myList, and displays: 5
Note that the items added to a list can be any expression. The expression is resolved before being added to the list:
var temperature = 22; var sky = "sunny"; var weatherListing = new Array( ); weatherListing.push(temperature, sky); trace (weatherListing); // Displays: "22,sunny", not "temperature,sky"
The unshift( ) method is much like push( ), but it adds one or more elements to the beginning of the array, bumping all existing elements further along (i.e., the indexes of existing elements increase to accommodate the new elements at the beginning of the array). The syntax of unshift( ) follows the same style as all array methods:
arrayName.unshift(item1, item2,...itemn);
where item1, item2,...itemn are a comma-separated list of items to be added to the beginning of the array as new elements. Note that multiple items are added in the order that they were supplied. Here are some examples:
var flashVersions = new Array( ); flashVersions[0] = 5; flashVersions.unshift(4); // flashVersions is now [4, 5] flashVersions.unshift(2,3); // flashVersions is now [2, 3, 4, 5]
The unshift( ) method, like push( ), returns the new length of the array being enlarged.
The splice( ) method can add elements to, or remove elements from, an array. It is typically used to squeeze elements into the middle of an array (latter elements are renumbered to make room) or to delete elements from the middle of an array (latter elements are renumbered to close the gap). When splice( ) performs both of these tasks in a single invocation, it effectively replaces some elements with new elements (though not necessarily the same number of elements). Here's the syntax for splice( ) :
arrayName.splice(startIndex, deleteCount, item1, item2,...itemn)
where startIndex is a number that specifies the index at which element removal and optional insertion should commence (remember that the first element's index is 0); deleteCount is an optional argument that dictates how many elements should be removed (including the element at startIndex). When deleteCount is omitted, every element after and including startIndex is removed. The optional parameters item1, item2,...itemn are a comma-separated list of items to be added to the array as elements starting at startIndex.
Example 11-3 shows the versatility of the splice( ) method.
// Make an array... months = new Array("January", "Friday", "April", "May", "Sunday", "Monday", "July"); // Hmmm. Something's wrong with our array. Let's fix it up. // First, let's get rid of "Friday" months.splice(1,1); // months is now: // ["January", "April", "May", "Sunday", "Monday", "July"] // Now, let's add the two months before "April". // Note that we won't delete anything here (deleteCount is 0). months.splice(1, 0, "February", "March"); // months is now: // ["January", "February", "March", "April", "May", "Sunday", "Monday", "July"] // Finally, let's remove "Sunday" and "Monday" while inserting "June" months.splice(5, 2, "june"); // months is now: // ["January", "February", "March", "April", "May", "June", "July"] // Now that our months array is fixed, let's trim it // so that it contains only the first quarter of the year // by deleting all elements starting with index 3 (i.e., "April") months.splice(3); // months is now: ["January", "February", "March"]
Another useful feature of splice( ) is that it returns an array of the elements it removes. Thus it can be used to extract a series of elements from an array:
myList = ["a", "b", "c", "d"]; trace(myList.splice(1, 2)); // Displays: "b, c" // myList is now ["a", "d"]
If no elements are removed, splice( ) returns an empty array.
Like push( ), concat( ) adds elements to the end of an array. Unlike push( ), concat( ) does not modify the array on which it is invoked -- instead, concat( ) returns a new array. Furthermore, concat( ) can break arrays supplied as arguments into individual elements, allowing it to combine two arrays into a single, new array. Here's the syntax for concat( ) :
origArray.concat(elementList)
The concat( ) method appends the elements contained in elementList, one by one, to the end of origArray and returns the result as a new array, leaving origArray untouched. Normally, we'll store the returned array in a variable. Here, simple numbers are used as the items to be added to the array:
var list1 = new Array(11, 12, 13); var list2 = list1.concat(14, 15); // list2 becomes [11, 12, 13, 14, 15]
In this example, we use concat( ) to combine two arrays:
var guests = ["Panda", "Dave"]; var registeredPlayers = ["Gray", "Doomtrooper", "TRK9"]; var allUsers = registeredPlayers.concat(guests); // allUsers is now: ["Gray", "Doomtrooper", "TRK9", "Panda", "Dave"]
Notice that concat( ) separated the elements of the guests array in a way that push( ) would not have. If we had tried this code:
var allUsers = registeredPlayers.push(guests);
we'd have ended up with this nested array:
["Gray", "Shift", "TRK9", ["Panda", "Dave"]]
Furthermore, push( ) would have altered the registeredPlayers array, whereas concat( ) does not.
Note, however, that concat( ) does not break apart nested arrays (elements that are themselves arrays within the main array), as you can see from the following code:
var x = [1, 2, 3]; var y = [[5, 6], [7, 8]]; var z = x.concat(y); // Result is [1, 2, 3, [5, 6], [7, 8]]. // Elements 0 and 1 of y were not "flattened."
Copyright © 2002 O'Reilly & Associates. All rights reserved.