start page | rating of books | rating of authors | reviews | copyrights

Book HomeActionScript: The Definitive GuideSearch this book

11.8. Removing Elements from an Array

You can remove elements from an array using the delete operator, by reducing the length property of an array, or using one of the built-in array methods.

11.8.1. Removing Elements with the delete Operator

The delete operator sets an array element to undefined, using the following syntax:

delete arrayName[index]

where arrayName is any array, and index is the number or name of the element we want to set to undefined. The name delete is misleading, frankly. It does not remove an element from the array; it merely sets the target element's value to undefined. A delete operation, therefore, is identical to assigning the undefined value to an element. We can verify this by checking the length property of an array after deleting one of its elements:

var myList = ["a", "b", "c"];
trace(myList.length);  // Displays: 3
delete myList[2];
trace(myList.length);  // Still displays 3...the element at index 2 is undefined
                      // instead of "c", but it still exists

To truly delete elements, use splice( ) (to delete them from the middle of an array), or use shift( ) and pop( ) (to delete them from the beginning or end of an array). Note that delete behaves differently with object properties and named elements than with numbered elements. Using delete on them permanently destroys properties and named elements, leaving no trace of them.

11.8.2. Removing Elements with the length Property

Earlier we used the length property to add elements to an array. We can also set the array's length property to a number smaller than the current length in order to delete elements from the array (i.e., truncate the array):

var toppings = ["pepperoni", "tomatoes", "cheese", "green pepper", "broccoli"];
toppings.length = 3;
trace(toppings);  // Displays: "pepperoni,tomatoes,cheese"
                  // We trimmed elements 3 and 4 (the last two).

11.8.3. Removing Elements with Array Methods

Arrays come equipped with several built-in methods for removing elements. We've already seen how splice( ) can delete a series of elements from the middle of an array. The pop( ) and shift( ) methods are used to prune elements from the end or beginning of an array.

11.8.3.1. The pop( ) method

The pop( ) method is the antithesis of push( ) -- it removes the last element of an array. The syntax of pop( ) is simple:

arrayName.pop( )

(I don't know why, but I always think that "popping" an array is kinda funny.) Anyway, pop( ) decrements the array's length by 1 and returns the value of the element it removes. For example:

x = [56, 57, 58];
x.pop( );     // x is now [56, 57]

As we learned earlier, pop( ) is often used in combination with push( ) to perform LIFO stack operations. In Example 11-4, we use the siteHistory array to track a user's navigation through a site. When the user navigates to a new frame, we add his location to the array using push( ). When the user navigates back, we pop( ) his last location off of siteHistory, and send him to the preceding location. Example 11-4 may be downloaded from the online Code Depot.

Example 11-4. A Back Button with History

// CODE ON FRAME 1 OF OUR MOVIE
stop( );
var siteHistory = new Array( );

function goto(theLabel) {
  // If we're not already at the requested frame...
  if (theLabel != siteHistory[siteHistory.length - 1]) {
    // ...add the request to the history, then go to the requested frame
    siteHistory.push(theLabel);
    gotoAndStop(siteHistory[siteHistory.length - 1]);
  }
  trace(siteHistory);
}

function goBack( ) {
  // Remove the last item in the history
  siteHistory.pop( );
  // If there is anything left in the history...
  if (siteHistory.length > 0) {
    // ...go to the most recent frame
    gotoAndStop(siteHistory[siteHistory.length - 1]);
  } else {
    // ...otherwise go home
    gotoAndStop("home");
  }
  trace(siteHistory);
}

// CODE ON A NAVIGATION BUTTON
on (release) {
  goto("gallery");
}

// CODE ON THE BACK BUTTON
on (release) {
  goBack( );
}

11.8.3.2. The shift( ) method

Remember unshift( ), the method we used to add an element to the beginning of an array? Meet its alter ego, shift( ), which removes an element from the beginning of an array:

arrayName.shift( )

Not as funny as pop. Oh well.

Like pop( ), shift( ) returns the value of the element it removes. The remaining elements all move up in the pecking order toward the beginning of the array. For example:

var sports = ["hackey sack", "snowboarding", "inline skating"];
sports.shift( );  // Now ["snowboarding", "inline skating"]
sports.shift( );  // Now ["inline skating"]

Because shift( ) truly deletes an element, it is more useful than delete for removing the first element of an array. We can also use shift( ) to limit the range of a list. For example, suppose we're calculating the frame rate of a movie. We push( ) the current time onto an array after each frame renders. To limit the size of our array to the most recent 10 time samples, we shift( ) the oldest time off as necessary. To find the frame rate, we average the times in our array. Example 11-5 shows the technique.

Example 11-5. Calculating the Frame Rate of a Movie

// Create our time measurement array in a movie clip
onClipEvent(load) {
  var elapsedTime = new Array( );
}

// Use an enterFrame clip event to measure the time after each frame
onClipEvent(enterFrame) {
  // Add the current time to elapsedTime
  elapsedTime.push(getTimer( ));

  // If we have enough samples to calculate an average...
  if (elapsedTime.length > 10) {
    // ...remove the oldest time from elapsedTime
    elapsedTime.shift( );

    // Average the number of elapsed milliseconds per frame
    elapsedAverage = (elapsedTime[elapsedTime.length - 1] - 
                     elapsedTime[0]) / elapsedTime.length;

    // To find the frames per second, divide 1 second by the elapsed average
    fps = 1000 / elapsedAverage;
    trace("current fps " + fps);
  }
}

11.8.3.3. The splice( ) method

Earlier we learned that splice( ) can both remove elements from and add elements to an array. Since we've already looked at splice( ) in detail, we won't reexamine it here. However, given our current context, we should specifically demonstrate splice( ) 's element-removal capabilities:

var x = ["a", "b", "c", "d", "e", "f"];
x.splice(1,3);  // Removes elements 1, 2, and 3, leaving ["a", "e", "f"]
x.splice(1);    // Removes elements 1 through the end leaving just ["a"]


Library Navigation Links

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