Accessing Arrays


After you have a new array ready, you can add, remove, and access elements in it. The syntax for an access is as follows :

 myArray[  index  ]; 

The access begins with the name of the array followed by an index contained in brackets (remember that the index indicates which of the variables in the block to access). That whole expression will return the value of the element found at position index . You can use this same syntax to add and remove elements from an array. Consider the following:

 myArray = new Array();  myArray[0] = 100;   trace( myArray[0] + 15 );  
Caution  

The first element of an array has an index of 0. It works that way for historical reasons involving a memory offset. Although this is not necessary in a language like ActionScript, it has become convention in modern programming languages to start at an index of 0. Further, it makes some of the mathematical calculations you can do with an index much easier.

The result of this script would be the output 115. That's because we first assign the array's 0 element a value of 100. Then we add 15 and output the result. You might be wondering why we didn't use a normal variable for something like that. You're right ”we could have. But when we understand how to use arrays, they will provide us some great utility. Consider this script:

 for(i=0; i<10; ++i){     myArray[i] = i*10; } 

That script fills the first 10 locations in the array with the values 0, 10, 20, 30, 40, and so on. It's common to use arrays in for loops , with the loop index used as the array index. That gives you a concise way to iterate through all the elements in an array. A representation of the array created by the preceding script can be seen in Figure 5.2.

click to expand
Figure 5.2: An array populated with a for loop using the script myArray[i] = i*10; .

The real beauty of an array is the fact that you can use it to hold a variable number of elements. For example, when you have hundreds of alien invaders , you might choose to keep them in an array. By simply adding new aliens to your array when you spawn new ones and removing those aliens that the player blasts, you can easily keep track of thousands of aliens during the life of your game.




Macromedia Flash MX 2004 Game Programming
Macromedia Flash MX 2004 Game Programming (Premier Press Game Development)
ISBN: 1592000363
EAN: 2147483647
Year: 2004
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net