This article mainly introduces JavaScript for the use of the loop, is the basic knowledge of JS learning, need friends can refer to the
We've seen that while loops have different variants. This chapter will introduce another popular loop called A For loop.
For loop
The For loop is the most compact form of the loop and consists of the following three important parts:
The initial value of the loop initialization counter. Before the initialization statement execution loop begins.
A test statement that tests if a given condition is true or false. If the condition is true, the code given in the loop that will be executed, otherwise the loop exits.
Loop statement, you can increase or decrease the counter.
You can separate the lines in all three sections with semicolons.
Grammar
?
1 2 3 |
for (initialization. test condition; Iteration statement) {statement (s) to was executed if test condition is true} |
Example:
The following example illustrates a basic for loop:
?
1 2 3 4 5 6 7 8 9 10 11 |
<script type= "Text/javascript" > <!--var count; document.write ("Starting Loop" + "<br/>"); for (count = 0, Count < count++) {document.write ("Current count:" + count); document.write ("<br/>"); } document.write ("Loop stopped!"); --> </script> |
This produces the following result, similar to the while loop:
?
1 2 3 4 5 6 7 8 9 10 11-12 |
Starting Loop current count:0 current count:1 current count:2 current Count:3 current Count:4 current Count:5 Current Count:6 current Count:7 current Count:8 current Count:9 Loop stopped! |