JavaScript For loop example teaching

 In most programming languages, loops often play a very important role. Some actions can be easily repeated through loops. In JavaScript, loops include for loop and for loop. While loop (while loop), during the execution of a program, there is no stipulation which loop must be used. It depends on your needs at the time. Generally speaking, when we know how many times the loop will run, we will Use the For loop, and when the number of loops is uncertain, use the while loop.


A javascript for loop should be written like this

for( variable = initial value; variable <= end value; variable + increase value) {
 program to be executed
}

This may seem a bit abstract, just look at the example introduction, use For Loop to run from 1 to 3 and display it on the web page
<script language="JavaScript">
 for (i=0; i<=3; i=i+1) {
  document.write("the"+ i + "ring<br>");
 }
</script>
The result is the

first circle,
the second circle,
the third circle.

In this example, we can see that we set a for loop, the variable value is i, the initial value is 0, every time i is less than 3, then i will increase by 1 and then Run once in a circle. The document.write in the for loop is just to display the string on the web page.

Post a Comment

0 Comments