JavaScript flow control (loop)

JavaScript flow control (loop)

1. for loop

In a program, a group of statements that are repeatedly executed is called a loop body. Whether the execution can continue depends on the termination condition of the loop. A statement consisting of a loop body and the loop termination condition is called a loop statement.
The for loop is mainly used to loop certain code several times, usually related to counting.

Its grammatical structure is as follows:

for(initialize variable; conditional expression; operation expression){
    //loop body}

  • Initialize variables: Usually used to initialize a counter. This expression can use the var keyword to declare a new variable, which helps us record the number of times.
  • Conditional expression: used to determine whether each loop can be executed. If the result is true , continue the loop, otherwise exit the loop.
  • Operation expression: An expression that is executed at the end of each loop. Typically used to update or increment a counter variable. Of course, decrementing the variable is also possible.

For example, use a for loop to execute the same code: output 'I love learning front-end' ten times.

for(i=0;i<10;i++){
    console.log('I love learning front-end');
}

The output is:

Another example is using a for loop to execute different codes: Output a person's age from 1 to 20.

for (var i = 1; i <= 20; i++) {
    console.log('This person is' + i + 'years old');
}

The output is:

2. Double for loop

Loop nesting refers to the grammatical structure of defining another loop statement in a loop statement. For example, in a for loop statement, you can nest another for loop. We call such a for loop statement a double for loop.

Grammatical structure:

for (outer loop start; outer loop condition; outer loop operation expression) {
    for (inner loop start; inner loop condition; inner loop operation expression) {  
       The code to be executed;
   }
}

  • The inner loop can be regarded as the statement of the outer loop
  • The execution order of the inner loop must also follow the execution order of the for loop
  • The outer loop executes once, and the inner loop executes all the times

For example, print five rows and five columns of stars.

core:

  • (1) The inner loop is responsible for printing five stars in a row
  • (2) The outer loop is responsible for printing five lines

var star = '';
for (var j = 1; j <= 3; j++) {
    for (var i = 1; i <= 3; i++) {
      star += '☆'
    }
    // Add a line break every time 5 stars are reached star += '\n'
}
console.log(star);

The running results are:

3. While loop

The while statement can execute a specified section of code in a loop while the conditional expression is true, and end the loop when the expression is not true.

The syntax of while statement is as follows:

while (conditional expression) {
    // loop body code}

Implementation ideas:

  • (1) Execute the conditional expression first. If the result is true , execute the loop body code; if it is false , exit the loop and execute the following code
  • (2) Execute loop body code
  • (3) After the loop body code is executed, the program will continue to judge the execution condition expression. If the condition is still true , the loop body will continue to execute until the loop condition is false , and the entire loop process will end.

It should be noted that:

When using while loop, be sure to note that it must have an exit condition, otherwise it will become an infinite loop.
The difference between while loop and the for loop is that while loop can make more complex conditional judgments, such as judging the username and password

For example, use a while loop to calculate the sum of all integers between 1 and 100.

var sum = 0;
var i = 0;
while(i<=100){
    sum += i;
    i++;
}
console.log(sum);

The output is:

4. do while loop

do… while statement is actually a variation of while statement. The loop will execute the code block once, and then judge the conditional expression. If the condition is true, the loop body will be executed repeatedly, otherwise the loop will be exited.

The grammatical structure of the do... while statement is as follows:

do {
    // Loop body code - repeatedly execute the loop body code while the conditional expression is true } while(conditional expression);

Implementation ideas:

  • Execute the loop code once
  • Execute the conditional expression again. If the result is true , continue to execute the loop body code. If it is false , exit the loop and continue to execute the following code.

Note: Execute the loop body first, then judge, you will find that the do...while loop statement will execute the loop body code at least once

For example: Calculate the sum of all integers between 1 and 100 through a do while loop.

var sum = 0;
var i = 0;
do{
    sum += i;
    i++;
}while(i<=100)
console.log(sum);

5. Cycle Summary

There are for loops, while , and do while loops in JS.
The three loops can be used interchangeably in many cases. If it is used to count the number of times, the three loops are basically the same, but we prefer to use for
while and do…while can make more complex judgment conditions and are more flexible than for loops.
The execution order while and do…while is different. While first judges and then executes, while do...while first executes once and then judges and executes
The execution times of while and do…while are different. do...while will execute the loop body at least once, while while may not execute it once.

6. continue break

1. The continue keyword

The continue keyword is used to immediately jump out of the current loop and continue to the next loop (the code after continue in the current loop body will be executed one less time).
For example: if you eat 5 buns and the third one has a bug, you should throw away the third one and continue to eat the fourth and fifth buns.

The code implementation is as follows:

for (var i = 1; i <= 5; i++) {
     if (i == 3) {
         console.log('This bun has bugs, throw it away');
         continue; // Jump out of this loop, the one that jumps out is the third loop}
      console.log('I am eating the ' + i + 'th bun');
 }

2. break keyword

The break keyword is used to immediately jump out of the entire loop (end of the loop).

For example, if you eat 5 buns and find half of the third one has a bug in it, you don't eat the rest. The code is as follows:

for (var i = 1; i <= 5; i++) {
   if (i == 3) {
       break; // Directly exit the entire for loop and jump to the statement below the entire for }
   console.log('I am eating the ' + i + 'th bun');
 }

This is the end of this article about JavaScript flow control (loop). For more relevant JavaScript flow control content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript flow control (branching)
  • JavaScript flow control statement collection
  • A simple example of generating a multiplication table using JSP
  • js realizes the gorgeous effect of the multiplication table
  • Writing the multiplication table in JavaScript (two optional)
  • This article teaches you how to use JavaScript to use process control to print the multiplication table

<<:  Fall in love with the simple CSS details, although insignificant, can improve efficiency

>>:  Absolute path URL and relative path URL in html and subdirectory, parent directory, root directory

Recommend

How to install pip package in Linux

1. Download the pip installation package accordin...

How to query data from multiple unrelated tables and paging in Mysql

Mysql multiple unrelated tables query data and pa...

Analysis of the Principles of MySQL Slow Query Related Parameters

MySQL slow query, whose full name is slow query l...

Detailed explanation of generic cases in TypeScript

Definition of Generics // Requirement 1: Generics...

Common tags in XHTML

What are XHTML tags? XHTML tag elements are the b...

Explanation of the concept and usage of Like in MySQL

Like means "like" in Chinese, but when ...

Summarize the common application problems of XHTML code

Over a period of time, I found that many people d...

Vue3 (V) Details of integrating HTTP library axios

Table of contents 1. Install axios 2. Use of axio...

A practical record of restoring a MySQL Slave library

Description of the situation: Today, I logged int...

New ideas for time formatting in JavaScript toLocaleString()

Table of contents 1. Conventional ideas for time ...

How to install mysql via yum on centos7

1. Check whether MySQL is installed yum list inst...

Detailed explanation of Axios asynchronous communication in Vue

1. First, we create a .json file for interactive ...

One minute to experience the smoothness of html+vue+element-ui

Technology Fan html web page, you must know vue f...