46
Chapter 2: Director Scripting Essentials
•
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
Copying arrays
Assigning an array to a variable and then assigning that variable to a second variable does not
make a separate copy of the array.
For example, the first statement below creates an array that contains the names of two continents,
and assigns the array to the variable
landList
. The second statement assigns the same list to a
new variable
continentList
. In the third statement, adding
Australia
to
landList
also
automatically adds
Australia
to the array
continentList
. This happens because both variable
names point to the same Array object in memory.
// JavaScript syntax
var landArray = new Array("Asia", "Africa");
var continentArray = landArray;
landArray.push("Australia"); // this also adds "Australia" to continentList
To create a copy of an array that is independent of another array:
•
Use the Array object’s
slice()
method.
For example, the following statements create an array and then use
slice()
to make an
independent copy of the array.
// JavaScript syntax
var oldArray = ["a", "b", "c"];
var newArray = oldArray.slice(); // makes an independent copy of oldArray
After
newArray
is created, editing either
oldArray
or
newArray
has no effect on the other.
Summary of Contents for DIRECTOR MX 2004-DIRECTOR SCRIPTING
Page 1: ...DIRECTOR MX 2004 Director Scripting Reference...
Page 48: ...48 Chapter 2 Director Scripting Essentials...
Page 100: ...100 Chapter 4 Debugging Scripts in Director...
Page 118: ...118 Chapter 5 Director Core Objects...
Page 594: ...594 Chapter 12 Methods...
Page 684: ...684 Chapter 14 Properties See also DVD...
Page 702: ...702 Chapter 14 Properties See also face vertices vertices flat...
Page 856: ...856 Chapter 14 Properties JavaScript syntax sprite 15 member member 3 4...
Page 1102: ...1102 Chapter 14 Properties...