Sunday, November 15, 2009

The For Loop and For...In Loop


Sometimes you need to execute code repeatedly for a given number of times. The For Loop and For...In Loop structures accomplish this. These are similar to AppleScript's Repeat and Repeat In structures.

<html>
<body>
<script language=javascript>

var degreesFahrenheit = new Array (212, 32, -459.15);
var degreesCelsius = new Array ();
var repeatCount;

for (repeatCount = 0; repeatCount <= 2; repeatCount++)
{
degreeCelsius [repeatCount] = 5/9 * (degreeFahrenheit [repeatCount] - 32)
}

for (repeatCount = 2; repeatCount >= 0; repeatCount--)
{
document.write ("Value " + repeatCount + " was " + degreeFahrenheit [repeatCount] + " degrees Fahrenheit");
document.write (" which is " + degreeCelsius [repeatCount] + " degrees Celsius<br>");
}

</script>

</body>
</html>



This statement sets the parameters for the loop. The parameters are separated by a semicolon:

for (repeatCount = 0; repeatCount <= 2; repeatCount++)


The first two parameters, repeatCount = 0; repeatCount <= 2;
, set the loop count to start at 0 and end at 2.


The last parameter, repeatCount++
, increments the loop by 1 each time it loops through. As you might have surmised, repeatCount--
would increment the loop by 1 each time from from a higher initial value such as 3.

The For...In loop is used mainly with arrays. It makes it possible to loop through arrays without needing to know ahead of time how many elements are contained in the array.

Example:


var textItemArray = new Array("Books", "Magazines","Newspapers");
var theTextItem
for (theTextItem in textItemArray)
{
alert(textItemArray [theTextItem])
}



This loops through the elements in textItemArray
and displays an alert containing each.

Learning How to Write JavaScript Code' to Technorati Favorites



Want HTML Code? Go to: http://write-html-code.blogspot.com/

No comments:

Post a Comment