Book HomeActionScript: The Definitive GuideSearch this book

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

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

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

11.7.3. 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, "Objects and Classes", that a method is a function that operates on an object.)

11.7.3.1. The push( ) method

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"

Pushing, Popping, and Stacks

The push( ) method takes its name from a programming concept called a stack. A stack can be thought of as a vertical array, like a stack of dishes. If you frequent cafeterias or restaurants with buffets, you'll be familiar with the spring-loaded racks that hold plates for the diners. When clean dishes are added, they are literally pushed onto the top of the stack and the older dishes sink lower into the rack. When a customer pops a dish from the stack, he is removing the dish that was most recently pushed onto the stack. This is known as a last-in-first-out (LIFO) stack and is typically used for things like history lists. For example, if you hit the Back button in your browser, it will take you to the previous web page you visited. If you hit the Back button again, you'll be brought to the page before that, and so on. This is achieved by pushing the URL of each page you visit onto the stack and popping it off when the Back button is clicked.

LIFO stacks can also be found in real life. The last person to check her luggage on an airplane usually receives her luggage first when the plane lands because the luggage is unloaded in the reverse order from which it was loaded. The early bird who checked his luggage first is doomed to wait the longest at the luggage conveyor belt after the plane lands. A first-in-first-out (FIFO) stack is more egalitarian -- it works on a first-come-first-served basis. A FIFO stack is like the line at your local bank. Instead of taking the last element in an array, a FIFO stack deals with the first element in an array next. It then deletes the first element in the array and all the other elements "move up," just as you move up in line when the person in front of you is deleted (i.e., she is either served and then leaves, or chooses to leave in disgust because she is tired of waiting). Therefore, the word push generally implies that you are using a LIFO stack, whereas the word append implies that you are using a FIFO stack. In either case, elements are added to the "end" of the stack; the difference lies in from which end of the array the element for the next operation is taken.

11.7.3.2. The unshift( ) method

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.

11.7.3.3. The splice( ) method

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.

Example 11-3. Using the splice( ) Array 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.

11.7.3.4. The concat( ) method

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


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.