JavaScript for loop

Loops can execute a block of code a specified number of times.


JavaScript Loops

If you want to run the same code over and over again, with the same value each time Different, then it is very convenient to use loops.

JavaScript supports different types of loops:

  • for - loop a block of code a certain number of times

  • for/in - Loop through the properties of the object

  • while - Loop through the specified code block when the specified condition is true

  • do/ while - also loops the specified code block when the specified condition is true


##For loop

The for loop is a tool that you often use when you want to create a loop.

The following is the syntax of the for loop:

for (statement 1; statement 2; statement 3)

{
Executed code block
}

Statement 1 (code block) executes starts before starting.

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

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

Example

    php中文网(php.cn) 

点击按钮循环代码5次。

Run the program to try it out


From the above example, you can see:

Statement 1 sets the variable (var i=0) before the loop starts.

Statement 2 defines the conditions for the loop to run (i must be less than 5).

Statement 3 increments a value (i++) each time the block of code has been executed.


Statement 1

Usually we use statement 1 to initialize the variables used in the loop (var i=0) .

Statement 1 is optional, which means you can not use statement 1.

You can initialize any (or multiple) values in statement 1:

    php中文网(php.cn) 

Run the program to try it


You can also omit statement 1 (such as When the value has been set before the loop starts):

Example

    php中文网(php.cn) 

Run the program to try it


Statement 2

Normally statement 2 is used to evaluate the condition of the initial variable.

Statement 2 is also optional.

If statement 2 returns true, the loop starts again, if it returns false, the loop ends.

Note: If you omit statement 2, you must provide a break inside the loop. Otherwise the cycle cannot be stopped. This may crash the browser.


Statement 3

Normally statement 3 will increase the value of the initial variable.

Statement 3 is also optional.

Statement 3 has many uses. The increment can be negative (i--), or larger (i=i+15).

Statement 3 can also be omitted (for example, when there is corresponding code inside the loop):

Example

    php中文网(php.cn) 

Run Try the program


For/In loop

JavaScript for/in statement loops through the properties of the object:

Example

    php中文网(php.cn) 

点击下面的按钮,循环遍历对象 "person" 的属性。

Run the program and try it


We will explain the while loop and do/while loop to you in the next chapter.



Continuing Learning
||
php中文网(php.cn)
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!