Javascript for Loop


The JavaScript for loop is used to iterate over a piece of code with the following syntax:

for (expr1; expr2; expr3) {
   statement
}

The for loop is usually used when the number of executions has been determined. The following example outputs 1 to 10:

var i=1
for (i = 1; i <= 10; i++) {
    document.write(i + "<br /> ")
}

operation result:

1
2
3
4
5
6
7
8
9
10

For loop syntax explaination

  1. The first expression (expr1) is evaluated unconditionally at the beginning of the loop
  2. Expr2 is evaluated before each iteration of the loop. If the value is TRUE, the loop is continued and a nested loop statement is executed. If the value is FALSE, the loop is terminated.
  3. Expr3 is evaluated (executed) after each iteration.
  4. Each expression can be empty. If expr2 is empty, it will loop infinitely, but you can break through the end of the loop, as in the following example:
var i=1
for (i = 1; ; i++) {
    if (i > 10) {
        break;
    }
    document.write(i + "<br />");
}

The example still outputs 1 to 10, but using the if conditional judgment, when i> 10, the loop ends.

Note

In the use of loops, we usually have to pay attention to not infinite loop caused by the program "dead", also pay attention to the loop conditions (loop to determine the expression) to ensure that the correct loop results.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook