|[ 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:
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:
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:
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.
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 member member member member member
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.
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 ]|