Home > Web Front-end > JS Tutorial > Detailed explanation of the use of for loop in JavaScript_Basic knowledge

Detailed explanation of the use of for loop in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:56:45
Original
1451 people have browsed it

We have seen that there are different variations of while loops. This chapter will introduce another popular loop called the for loop.
for loop

The for loop is the most compact form of a loop and consists of the following three important parts:

  1. Initial value of loop initialization counter. The initialization statement is executed before the loop begins.
  2. Test statement that will test if the given condition is true or false. If the condition is true, then the code given in the loop will be executed, otherwise the loop will exit.
  3. Loop statement that can increase or decrease the counter.

You can separate all three parts on a line with semicolons.
Grammar

for (initialization; test condition; iteration statement){
   Statement(s) to be executed if test condition is true
}

Copy after login

Example:

The following example illustrates a basic for loop:

<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
 document.write("Current Count : " + count );
 document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>

Copy after login

This will produce the following result, which is similar to a while loop:

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! 

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template