Think of an array like a chest of drawers. Each drawer in the chest is numbered, and each drawer may contain data, whether that data be a string, a number, a boolean, an object, or another array. You access the data in the "drawers" of an array via the "drawer" number.
Here is a conceptual picture of an array:
In the above illustration, I have created an array named fred. The array, fred, has four "drawers" or positions, numbered sequentially starting from 0 (array positions always start at 0). In the 0 position (the first drawer) of fred, there is a string, "Hi". In the 1 position (the second drawer) of fred, there is a number, 127. In the 2 position (the third drawer) of fred, there is a boolean value, true. In the 3 position (the fourth drawer) of fred, there is another string, "Wow".
var fred = new Array();
There are several ways that I could then initialize the contents of the positions in fred. The most characteristic means of doing so is by using the ARRAY ACCESS OPERATOR (
var fred = new Array(); fred = "Hi"; fred = 127; fred = true; fred = "Wow";
I place the array access operator (
) next to the name of the pertinent array (fred), and put the number of the array position that I want between the square-braces of the operator. I use the "gets" or "assignment" operator to put information into each of the array positions. Again, any type of data may be placed into an array position, including objects or other arrays.
I could then PULL or EXTRACT information from a position in the array using the same array access operator (
var myData = fred;
In the above example, I have pulled information from the array fred at its 0 position, and placed that data into the variable, myData. If this array were the same as the one in the previous example, myData would now contain the string, "Hi".
Note on pronunciation:
fred would be referred to as "fred sub zero",
fred would be referred to as "fred sub one", etc.
There is a second way to initialize arrays which involves passing arguments to the Array() constructor during the declaration of the array.
var fred = new Array("Hi", 127, true, "Wow");
As you can see in the above example, I have passed all of my initial values for the array as arguments of the Array constructor; this is a terrific shorthand for initializing arrays quickly and easily.
Copyright © 2001 Michael Masumoto. All Rights Reserved.