| |
|
|
|
|
|
|
|
Using arrays in actionscript
What is an array ?

|
An array can be compared to a chest with drawers. The chest itself doesn't contain the content, it contains the drawers, the drawers hold the content. The chest organizes the drawers into a single unit.
An array is a collection of structured data, a list of items. Arrays are used to store and manipulate ordered lists of information.
|
|
Creating an array

We can create a new array with a data literal like :
var myChest =
["cup","ball","hat","gloves","pen"];
|
or using the built-in array constructor
function Array() like below :
var myChest =
new Array("cup","ball","hat","gloves","pen");
|
To create an array with the Array() constructor we need to use the new operator followed by the word Array.
var myChest = new Array();
|
var myChest = new Array(10);
|
An array can contain any number of items including items of different types we could have a mix of strings and numbers like in the example below :
| var myChest = ["cup",10,"hat","gloves",4]; |
|
Accessing the elements of an array

if we want to access a particular element of an array we have created we need to specify the array identifier followed by the element's index within square brackets : arrayName[elementNumber]
in the example below we trace the first element of the array myChest :
var myChest = new Array("cup","ball","hat","gloves","pen");
trace(myChest[0]);
|
The first element's index of an array is 0 and not 1. The last element's index of an array is the array length minus 1.
the code below retrieves all the elements of myChest
and trace them to the output window :
var myChest = new Array("cup","ball","hat","gloves","pen");
for(var i=0;i<=myChest.length-1;i++){
trace(myChest[i]);
}
|
The property length
retrieves the length of an array. As stated before we subtract 1 from
myChest .length to display the last element of the array. If we don't substract 1 from myChest .length the
loop will run 5 times and will display undefined on the last run because there is no
element myChest[5], the last one being
myChest[4].
|
|
|
|
If you think this page is providing useful information, don't hesitate to leave a comment.
|
|
|
|
|
|
|
|
|
Copyright ©2006-2008 flashvalley.com - All rights reserved |
|