Usage of JS for loop statement

The JS for loop is suitable for use when the number of loops is known, and the syntax format is as follows:

for(initialization; condition; increment) {     // code to execute }

The for loop contains three optional expressions initialization, condition and increment, where:

  • initialization: declares an expression or a variable, we usually call this step "initializing the counter variable", and it will only be executed once during the loop;
  • condition: It is a conditional expression, which has the same function as the conditional expression in the while loop. It is usually used to compare with the value of the counter to determine whether to loop. The number of loops can be set through this expression;
  • increment: An expression used to update (increment or decrement) the value of the counter after each loop.

The sample code is as follows:

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

Running results:
1 2 3 4 5 6 7 8 9 10

In the above code, it will be executed before the loop starts var i = 1;, and the variable i will be used as a counter; then judge i <= 10whether it is true, if it is true, execute { }the code in progress, if it fails, exit the for loop; after each loop execution is completed, perform i++the operation , which updates the value of the counter.

[Example] Use the for loop to traverse the contents of the array:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
for(var i = 0; i < fruits.length; i++) {
    document.write(fruits[i] + "&emsp;");
}

Running results:
Apple Banana Mango Orange Papaya

Three expressions in JS for loop

The three expressions in parentheses in the JS for loop can be omitted, but the semicolon used to separate the three expressions cannot be omitted.

As shown in the following example:

// 省略第一个表达式
var i = 0;
for (; i < 5; i++) {
    // 要执行的代码
}
// 省略第二个表达式
for (var y = 0; ; y++) {
    if(y > 5){
        break;
    }
    // 要执行的代码
}
// 省略第一个和第三个表达式
var j = 0;
for (; j < 5;) {
    // 要执行的代码
    j++;
}
// 省略所有表达式
var z = 0;
for (;;) {
    if(z > 5){
        break;
    }
    // 要执行的代码
    z++;
}

JS for loop nesting

No matter what kind of loop it is, it can be nested (that is, define one or more loops in a loop). Let's take the for loop as an example to demonstrate the nested use of loops:

for (var i = 1; i <= 9; i++) {
    for (var j = 1; j <= i; j++) {
        document.write(j + " x " + i + " = " + (i * j) + "&emsp;");
    }
    document.write("<br>");
}

 

Guess you like

Origin blog.csdn.net/weixin_65607135/article/details/126820778