Tuesday, 6 December 2011

Accidents


Creating an Array

There are a number of methods for creating an array. You can use the same instantiation method used for other AS3 classes by using the new keyword with the class name, and have the contents of you array passed as values between the brackets, as shown in the example code below:
var myArray:Array = new Array("Flash", "ActionScript", "Republic of Code");
Alternatively, ActionScript allows you to use a shorter technique by using the square brackets [] to automatically instantiate an array:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
Both of these codes create the same exact thing. Most developers tend to use the shorthand method though.

Accessing Elements in array

The advantage of using arrays instead of variables is that you can access specific elements in the array without retrieving the whole thing. You can, if you want to, retrieve all the contents of an array by referring to its name:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
trace(myArray);
Testing this code should output the following: "Flash,ActionScript,Republic of Code".
To be able to retrieve a specific element in the array, you must refer to that element using its index. The index of an element within an array is its position in the list. Is it the first item? The second? or what is its position? What you have to know about this index is that it is zero relative. This means that the first item in the list is not as position1, but at position 0. The second would be at position 1, the third at position 2, etc.
Once you know the index of an element, you can simply use the square brackets [] to retrieve it. The code below retrieves the first element in our array:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
trace(myArray[0]);
Testing this code should output the following: "Flash".
If we wanted to retrieve the third element in the array, we do that by retrieving the item at index 2 not 3:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
trace(myArray[2]);
Testing this code should output the following: "Republic of Code".
What you have learnt so far should be enough for you to create and access contents within an array. The following sections will teach you to add and remove elements from an array.

No comments:

Post a Comment