Referencing Arrays

[ LiB ]

In order to ease into arrays, you should practice using them before learning how to create them. So, to that end, what would the array I described in the last section look like? It could look something like this:

 scoreNames 

Looks like a regular variable, eh? That's where the convenience comes in. If you were to "trace" this array with your trace command, you would see all of its elements. Take this for instance:

 trace(scoreNames); 

Of course, if you were to type this code in, you wouldn't get anythingthe array hasn't been created yet. You will see working examples soon, but first let's get the theory out of the way.

If you want to reference a specific element in an array, you would have to use an opening and closing bracket with an index number in between. To reference the first element in the array, you would type something like this in there:

 trace(scoreNames[0]); 

This would output the value of the first element in the array, scoreNames. If this is true, then why are we indexing the 0 element? All indexing starts at zerothat means that index 1 is element 2, and index 2 is element 3, and so on. This will seem awkward at first, but you will get used to it quick.

NOTE

CAUTION

Don't forget that indexing starts at zero! I'll remind you where I think it's necessary, but don't even think about sleeping on this fact. Just imagine the bugs that'll creep into your program if you access the wrong information from an array.

It's time to test yourself. Look at the following list of elements.

 ["Cathy", "25", "David", 23, "Eddie", 24] 

In a program, I would treat these as pairs, but they still have to be referenced individually. They could easily be the person and the person's age, respectively. In this case, to reference Eddie's age, you would have to go through index 5. Get it? It's the sixth element. Try to guess the reference for the following:

 member[0] member[4] member[2] member[3] member[1] member[5] 

If you answered "Cathy, Eddie, David, 23, 25, 24," then you're on the money! Remember that the only reason you got these answers is because the first index starts at 0.

NOTE

NOTE

Keep in mind that even though the last element in this array is index 5, its length is still 6 because it has six elements in it. I know this seems obvious, but sometimes careless mis takes are made when you do not pay attention to this fact.

[ LiB ]


Game Development with ActionScript
Game Development with ActionScript
ISBN: 1592001106
EAN: 2147483647
Year: 2004
Pages: 162
Authors: Lewis Moronta

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