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

Removing Elements from an Array

To remove elements from an array, we use one of the following techniques:

  • Delete the specific element with the delete operator

  • Decrease the array's length variable

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

The following sections discuss these techniques in detail.

Removing Elements with the delete Operator

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

delete theArray[index]

In the preceding code, theArray is a reference to an array, and index is the number or name of the element whose value should be set to undefined. The name delete is, frankly, misleading. It does not remove the numbered 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 variable of an array after deleting one of its elements:

var list = ["a", "b", "c"];
trace(list.length);  // Displays: 3
delete list[2];
trace(list.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).

Removing Elements with the length Variable

To delete elements from the end of the array (i.e., truncate the array), we can set the array's length variable to a number smaller than the current length:

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