ArraysThe usage of
arrays in actionscript is nearly the same like the in other programming languages. However, there are some fine technical intricacies to point out.
First of all, the elements of an array in actionscript can be of different types. That means, you can put various types of elements in the same array. Following small example illustrates that:
public function Main()
{
var arr:Array = [ 1, "Two", { id:3 } ];
for (var i:uint = 0; i < arr.length; i++)
{
trace(typeof(arr[i]));
}
// Will result in the following output:
// number
// string
// object
}
Above’s code extract creates an array called arr which holds three elements. All elements are of a different type.The element at index 0 is of type Number, index 1 is of type String and finally index 2 is an object.
Another special thing about arrays in actionscript is that the memory of arrays are allocated automatically. That means, that you do not have to care about reserving memory if you want to add elements e.g. So theroretically each array has an unlimited amount of elements. Accessing an element which actually has never been created does not resolve in an error like in other programming languages (Array index out of bounce). Refer to the following example:
// Create an array which holds 2 elements
var arr:Array = new Array(2);
// Now try to access the third element
// This does not result in an error like in
// other programming languages
trace(arr[2]);
Although above’s code creates an array which should hold only 2 elements, we still can try to access the third element without retrieving an error. The third element is simply undefined (i.e. equals null). Keeping this in mind, the
length property returns actually the index of the last used element instead of the real amount of elements of the array. The final piece of code demonstrates the return values of length:
var arr:Array = new Array();
trace(arr.length);
arr[0] = 1;
trace(arr.length);
arr[100] = 2;
trace(arr.length);
// This code outputs:
// 0
// 1
// 101