AddThis Social Bookmark Button
 Using arrays in actionscript

What is an array ?
chest of drawers

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"];
// notice the comma separated list enclosed in square brackets

or using the built-in array constructor function Array() like below :
var myChest = new Array("cup","ball","hat","gloves","pen");
// notice the comma separated list enclosed but in normal brackets this time

To create an array with the Array() constructor we need to use the new operator followed by the word Array.
var myChest = new Array();
// create an empty array
var myChest = new Array(10);
// create an array with 10 empty placeholders
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]);
// display the string cup

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]);
}
// display the strings cup, ball, hat, gloves and pen in the output window

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].
AddThis Social Bookmark Button
If you think this page is providing useful information, don't hesitate to leave a comment.
flashvalley
 
Copyright ©2006-2008 flashvalley.com - All rights reserved