Arrays and Loops

Because arrays hold information in numeric sequence, loop logic is frequently used to read, rewrite, and/or otherwise change the data stored in an array.

There is one property of the Array object that you need to know about in order to use loop logic successfully when accessing arrays of an uncertain size: the length property. The length property of an instance of the Array object returns a number which is the number of positions of data stored in the array. Access the length property using dot syntax attached to the instance of the array object in question.

Example (assuming that fred is an instance of an Array object):

fred.length

Example (in context):

var fred = new Array("Hi", 127, true, "Wow");
alert(fred.length);

In the above example, fred.length returns a value of 4, the number of positions in the fred array. The alert method, then, would display a value of 4 because we passed fred.length as an argument to the alert method.

Using loop logic and the length property, we could access all of the information in fred.

Example:

var fred = new Array("Hi", 127, true, "Wow");

for (myCounter = 0; myCounter < fred.length; myCounter++) {
    var myData = fred[myCounter];
    alert(myData);
};

In the above example, we have set the FOR loop to run as long as myCounter is less than the length of fred, which will cause this particular loop to run 4 times (as long as myCounter is either 0, 1, 2, or 3. Now, since fred.length is equal to 4, as soon as myCounter gets to 4, the condition will become false, and the loop will end).

Inside the loop, I am using myCounter as a record of the position in the array that I am interested in. The first time through the loop, myCounter is equal to 0, so I will be pulling information from fred[0] and putting that into myData. I am then passing the contents of myData ("Hi") to the alert method, which will say "Hi". The next time through the loop, myCounter will be equal to 1, so I will be pulling information in my first line of code from fred[1] (the number 127), and putting that number into myData, etc etc.

We could remove one step from the above example by passing the return value of fred[myCounter] directly as an argument to the alert method, skipping the use of the variable, myData.

Example:

var fred = new Array("Hi", 127, true, "Wow");

for (myCounter = 0; myCounter < fred.length; myCounter++) {
	alert(fred[myCounter]);
};

Here is an example of this code in action. As an exercise, you may wish to recreate the function from this example, and see if you can get it to work yourself.

Main Menu