Java Reference
In-Depth Information
Finally, loopCounter is declared and will be used to keep track of which array index you are accessing
during your looping.
var degFahren = new Array(212, 32, -459.15);
var degCent = new Array();
var loopCounter;
Following this comes our fi rst for loop.
for (loopCounter = 0; loopCounter <= 2; loopCounter++)
{
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
}
In the fi rst line, you start by initializing the loopCounter to 0. Then the for loop's test condition,
loopCounter <= 2, is checked. If this condition is true, the loop executes for the fi rst time. After the
code inside the curly braces has executed, the incrementing part of the for loop, loopCounter++, will
be executed, and then the test condition will be re-evaluated. If it's still true, another execution of the
loop code is performed. This continues until the for loop's test condition evaluates to false, at which
point looping will end, and the fi rst statement after the closing curly brace will be executed.
The code inside the curly braces is the equation you saw in earlier examples, only this time you are
placing its result into the degCent array, with the index being the value of loopCounter .
In the second for loop, you write the results contained in the degCent array to the screen.
for (loopCounter = 2; loopCounter >= 0; loopCounter--)
{
document.write(“Value “ + loopCounter + “ was “ + degFahren[loopCounter] +
“ degrees Fahrenheit”);
document.write(“ which is “ + degCent[loopCounter] +
“ degrees centigrade<br />”);
}
This time you're counting down from 2 to 0 . The variable loopCounter is initialized to 2 , and the loop
condition remains true until loopCounter is less than 0 . This time loopCounter is actually decremented
each time rather than incremented, by means of loopCounter-- . Again, loopCounter is serving a
dual purpose: It keeps count of how many loops you have done and also provides the index position in
the array.
Note that in these examples, you've used whole numbers in your loops. However, there is no reason why
you can't use fractional numbers, although it's much less common to do so.
The for...in Loop
This loop works primarily with arrays, and as you'll see in the next chapter, it also works with something
called objects. It enables you to loop through each element in the array without having to know how many
elements the array actually contains. In plain English, what this loop says is “For each element in the array,
execute some code.” Rather than having to work out the index number of each element, the for...in loop
does it for you and automatically moves to the next index with each iteration (loop through).
Search WWH ::




Custom Search