Advertisement |
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);
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 position 1, 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]);
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]);
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.
0 comments: