This series experience video tutorial => click to watch: Bilibili

For loop

The basic grammar

The for statement is another form of the loop command, specifying initialization expressions, termination conditions, and incrementing expressions. Its format is as follows.

forInitialize the expression; Conditions; Incrementing expression) {statement}Copy the code

There are three parts separated by semicolons in the parentheses after the for statement.

  • Initial: Determines the initial value of a loop variable and is executed only once at the start of the loop.
  • Conditional expression (condition) : This conditional expression is executed at the beginning of each cycle and has only a value oftrueBefore continuing the loop.
  • Step: The last operation of each loop, usually used to increment a loop variable.
Initialize variable I → (condition is true → execute loop body → variable I increment) → (condition is true → execute loop body → variable I increment) → (condition is true → execute loop body → variable I increment) → (condition is not true → jump outforLoop)Copy the code
for (var i = 1; i <= 10; i++) {
  alter(i);
}
Copy the code

Any for loop, we can rewrite as a while loop.

var i = 1;
while (i <= 10) {
  alter(i);
  i++;
}
Copy the code

More for statements

Any or all of the three parts of the for statement can be omitted.

var i = 1
for (; i <= 3; i++) {
  console.log(i);
}
Copy the code
var i = 1
for (; i <= 3;) {console.log(i++);
}
Copy the code

The infinite loop for (; 😉 { console.log(‘Hello World’); } Notice the two for; Must exist, otherwise syntax errors will occur.

practice

  • Print the multiplication table
var str = ' '
for( var i = 1; i <= 9; i++) {
  for(var j = 1; j <= i; j++) {
    str += j + The '*' + i + '=' + (i * j) + ' '
  }
  str += '\n'
}
console.log(str);
Copy the code
  • Print Fibonacci numbers
var n = 7

var current = 0
var next = 1
var temp
for(var i = 0; i < n; i++) {
  temp = current
  current = next
  next += temp
}
console.log(current);
Copy the code

homework

  • Print hollow triangles using the for statement
     *
    * *
   *   *
  *     *
 *       *
***********
Copy the code