Director Help

Adding and deleting items in arrays

You can add or delete items in an array by using the following methods:

  • To add an item at the end of an array, use the Array object’s push() method.
  • To add an item at its proper position in a sorted array, use the Array object’s splice() method.
  • To add an item at a specific position in an array, use the Array object’s splice() method.
  • To delete an item from an array, use the Array object’s splice() method.
  • To replace an item in an array, use the Array object’s splice() method.

The following example illustrates using the Array object’s splice() method to add items to, delete items from, and replace items in an array:

// JavaScript syntax
var myArray = new Array("1", "2");
trace(myArray); displays 1,2

myArray.push("5"); // adds the value "5" to the end of myArray
trace(myArray); // displays 1,2,5

myArray.splice(3, 0, "4"); // adds the value "4" after the value "5"
trace(myArray); // displays 1,2,5,4

myArray.sort(); // sort myArray
trace(myArray); // displays 1,2,4,5

myArray.splice(2, 0, "3");
trace(myArray); // displays 1,2,3,4,5

myArray.splice(3, 2); // delete two values at index positions 3 and 4
trace(myArray); // displays 1,2,3

myArray.splice(2, 1, "7"); // replaces one value at index position 2 with "7"
trace(myArray); displays 1,2,7