Detailed Explanation of for Cycle and Double for Cycle in JavaScript

  • 2021-11-01 23:06:50
  • OfStack

for cycle

An for loop is a loop through the elements of an array.

Syntax:

for (initialization variable; Conditional expression; Iterative statement) {
The code block that needs to be executed;
}

Initialization variable: 1 is generally used to initialize and assign values to loop variables. Conditional expression: As a loop condition, an expression containing a comparison operator that limits the bounds of a loop variable. If the value of the loop variable exceeds the boundary, the execution of the loop statement is stopped. Iteration statement: Used to change the value of a loop variable to control the number of loops, usually incrementing or decrementing the value of a loop variable.

for loop execution sequence:

//1. Declare variables;
//2. Judge the loop execution condition;
//3. Code block execution;
//4. Variable self-increase;

Example: Find the even sum of 1-100


var num=0
    for(var i=0;i<=100;i+=2){  //i+=2  Meaning i=i+2
      num +=i         
    }
    console.log(" Even sum :"+num) 

Double for cycle

Loop nesting refers to the syntax structure of defining another loop statement in one loop statement. For example, in for loop statement, another for loop can be nested. Such for loop statement is called double for loop.

Syntax:

for (outer initialization variable; Outer conditional expression; Outer iterative statement) {
for (inner initialization variable; Inner conditional expression; Inner iterative statement) {
The code block that needs to be executed;
}
}

The inner loop can be regarded as the execution statement of the outer loop The outer loop executes once, and the inner loop executes all

Essence of double for cycle:

The outer for loop controls the height (number of rows) of the loop; The inner for loop controls the width of the loop (number of columns);

Example: Output 99 multiplication table


 for(var i= 0 ; i <=9 ; i++){
     for(var aa = 1 ; aa <i+1 ; aa++){
       document.write(aa+"*"+i+"="+i*aa);
     }
     document.write("<br />");
   } 

You can add a few styles to make it look nice (add an span element, define the width of the body part of body, change an span element to an inline-block inline block element, and set its fixed width)


<head>
<style> body{
    width:2000px;
  }
  span{
    display:inline-block;
    width:80px;
  } </style>
</head>
<body> 
<script> for(var i= 0 ; i <=9 ; i++){
     for(var aa = 1 ; aa <i+1 ; aa++){ document.write("<span>"+aa+"*"+i+"="+i*aa+"</span>");
     }
     document.write("<br />");
   } </script>
</body>

Summarize


Related articles: