Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Data and Data Types > About variables > Using variables in an application > Passing a variable by reference | |||
Because the Array and Object data types hold a reference to a value instead of containing its actual value, you need be careful when you work with arrays and objects.
The following example shows how to pass an object by reference. When you create a copy of the array, you actually create only a copy of the reference (or alias) to the array's contents. When you edit the contents in the second array, you modify both the contents of the first and second array because they both point to the same value.
var myArray:Array = new Array("tom", "josie");
var newArray:Array = myArray;
myArray[1] = "jack";
trace(myArray); // tom,jack
trace(newArray); // tom,jack
This ActionScript creates an Array object called myArray that has two elements. You create the variable newArray and pass a reference to myArray. When you change the second element of myArray to jack, it affects every variable with a reference to it. The trace() statement sends tom,jack to the Output panel.
|
NOTE |
|
Flash uses a zero-based index, which means that 0 is the first item in the array, 1 is the second, and so on. |
In the following example, myArray contains an Array object, so you pass the array to function zeroArray() by reference. The function zeroArray() accepts an Array object as a parameter and sets all the elements of that array to 0. It can modify the array because the array is passed by reference.
function zeroArray (theArr:Array):Void {
var i:Number;
for (i = 0; i < theArr.length; i++) {
theArr[i] = 0;
}
}
var myArr:Array = new Array();
myArr[0] = 1;
myArr[1] = 2;
myArr[2] = 3;
trace(myArr); // 1,2,3
zeroArray(myArr);
trace(myArr); // 0,0,0
The first trace() statement in this ActionScript displays the original contents of the myArray array (1,2,3). After you call the zeroArray() function and pass a reference to the myArray array, each of the array's values are overwritten and set to zero. The subsequent trace() statement displays the new contents of the myArray array (0,0,0). Because you pass the array by reference and not by value, you don't need to return the updated contents of the array from within the zeroArray() function.
For more information on arrays, see About arrays.
Flash CS3
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/9.0/main/00000661.html