Click to See Complete Forum and Search --> : Back again


Learnin
01-03-2004, 02:17 PM
Hello guys, I'm a noob at JS, and I'm learnin' from a book of wrox's.
I seem to have gotten stuck on one of the excersizes while learning the 'for loop':
_______________________________________
//<Script Language = JavaScript>

var degFahren = new Array(212, 32, -495.15);
var degCent = new Array();
var loopCounter;

for (loopCounter = 0; loopCounter <= 2; loopCounter++)
{
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
}

for (loopCounter = 2; loopCounter >= 0; loopCounter--)
{
document.write("Value " + loopCounter + " was " +
degFahren[loopCounter] + " degrees Fahrenheit");
document.write(" which is " + degCent[loopCounter] + "

degrees centigrade<BR>");
}
_______________________

The script converts temperatures. I did not understand how the second part worked, because in the second loop, loopCounter is assigned the value of 2, and therefore I did not understand why the degFahren[loopCounter] remained the value of 0, from the previous loop.
I would be grateful for you help, because helping begginers, is bringing a new person to the programming world.

olerag
01-03-2004, 04:40 PM
1. The "degFaren" array stores three farenheit constants.
2. The "degCent" array will store the 3 values from the
first array with corresponding celcius values. This is what
the first loop does and performs the task from element
position 0 thru 2.
3. The second loop merely displays the results of both
arrays however the loop is iterated in reverse of the first loop;
i.e., begins at element position 2 and ends at position 0.

Typically, loops aren't controlled in this manner. A better
way is to continue the loop as long as it's iteration value
is less than the length of the array.

This example shows an elementary use to:
a) Work with arrays.
b) Control loop iterations.
c) Perform a little math.
d) Display results on a web page in lieu of an alert.