The "for" loop
The "for" loop is a JavaScript "method"
that allows a certain action (ie: block of code) to be performed continuously in a
variably controlled fashion. It is very similar to a "while" loop in which lines
of JavaScript codes can be grouped together and repeated until a certain condition. A real
life example of a for loop would be as follows:
for length equal to 0 to length equal to 100
run!
Lets see the general syntax of for loops in JavaScript,
where y is an arbitrary variable:
for (y=0;y<=99;y++){
alert ("hi!")
}
The above example will alert "hi!" 100 times.
Lets look more closely at the heart of a "for" loop:
It consists of three components:
y=0 //The starting point of a for loop
y<=99 //The ending boundary of a for loop
y++ //How the "for" loop is
incremented. y++ means increment it by one step each time until the boundary.
The part that may be confusing is the last part,
"y++". Let's see the same above example, only this time, altering that
particular part:
for (y=0;y<=99;y=y+2){
alert ("hi!")
}
How many "hi" will be alerted? Well, 50 will,
because we are incrementing the "counter" not by 1, but by 2 this time. The
point is, you can determine however you want to increment the for loop by assigning a
different statement in the third component of the for loop.
Lets see a practical example of a "for" loop
than, where it is used to calculate the sum of 1+2+3+.....all the way up to the specified
number:
Here's the function that performs this calculation:
<script type="text/javascript">
function cal(){
var y=1
var temp=prompt("Please input a positive integer:")
for (x=2;x<=temp;x++){
y=y+x
}
alert("1+2+...+"+temp+"="+y)
}
</script>
The "for" loop is a major part of any programming
language, and JavaScript is no exception. For loops are commonly used with
arrays to loop through and process each array element effortlessly.
|