Javascript basic tutorial loop statement

Loop statement

##for Loop

for (Statement 1; Statement 2; Statement 3)

Execution statement;

}

## Statement 1 (code block) is executed before starts.

Statement 2 defines the conditions for running the loop (code block)

Statement 3 is executed after the loop (code block) has been executed

Let’s write an example below:

    循环语句 for 循环 
The above code calculates the sum of 1 to 10

We are writing an example: Look at the value change of i

    循环语句 for 循环 

In this way, the value of i will increase from 1 to 10. Friends, you can try

while loopwhile(condition){

Execution code block;

}

Example:

    循环语句 while 循环 

Note: Friends need to pay attention to the loop body The i++ is used to change the condition. If there is no i++ to change the condition, then i=1; will always satisfy the condition i<10, so the loop will continue to execute.

We call it an infinite loop

Below we use the while loop to write another example: calculate the sum of 1-10

    循环语句 while 循环 

The above code, so the output is also the sum of 1 to 10

Note: while Looping is to first judge the condition. If the condition is met, continue execution. If the condition is not met, jump out of the loop.

As shown in the figure above: the initial value of i is 1. This satisfies the condition, so the loop will be executed. Contents of the body If the conditions are not met, the loop body will be jumped out

For example, if i=11; when the following statement is executed, i++ will not be executed; and then execution continues, and the result sum;


do....while loopdo{

Execution statement;

}while(condition);

Let’s take a look at an example code:

    循环语句 do....while 循环 

Let’s analyze the above code. The value of i is first 11, enter the loop body, and output 11 times, and then execute i++, so that the value of i at this time is 12, and then judge that the condition is not met, jump out of the loop;

Note:

do while No matter whether the condition is met or not, it will be executed at least once

Next we will use do while to make a sum from 1 to 10. The code is as follows:

    循环语句 do....while 循环 

continue and breakThe break statement is used to break out of the loop.

continue is used to skip an iteration in a loop.

We have used the break statement in switch before. Next, we will explain the above code

    break 

in the example. You can comment out continue and write break to see the output of the two. the difference

break When i is exactly equal to 5, it will jump out of the loop directly, so it will only output 4 times.

continue When i is equal to 5, it will jump out of the loop and continue execution. Look at the output result, only the one equal to 5 The secondary value is not output

Continuing Learning
||
循环语句 for 循环
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!