Home >Web Front-end >JS Tutorial >Introduction to loop knowledge in JavaScript (code examples)
This article brings you an introduction to the knowledge of loops in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will help You helped.
for loop
Use the for loop when the number of runs of the script has been determined.
Syntax:
for (变量=开始值;变量<=结束值;变量=变量+步进值) { 需执行的代码 }
Explanation: The following example defines a loop program in which the starting value of i is 0. Each time the loop is executed, the value of i will be incremented by 1, and the loop will continue until i equals 10.
Note: The step value can be negative. If the step value is negative, you need to adjust the comparison operator in the for statement.
<html> <body> <script> var i=0 for (i=0;i<=10;i++) { document.write("The number is " + i) document.write("<br />") } </script> </body> </html>
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
The while loop is used to execute code in a loop when the specified condition is true.
while (变量<=结束值) { 需执行的代码 }
Note: In addition to <=, other comparison operators can also be used.
Explanation: The following example defines a loop program. The starting value of parameter i of this loop program is 0. The program runs repeatedly until i is greater than 10. The value of i will increase by 1 each time it is run.
<html> <body> <script> var i=0 while (i<=10) { document.write("The number is " + i) document.write("<br />") i=i+1 } </script> </body> </html>
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
do...while loop is a variant of while loop. The loop will first execute the code when it is first run, and then continue the loop when the specified condition is true. So it can be said that the do...while loop executes the code in it at least once, even if the condition is false, because the condition verification will not be performed until the code in it is executed.
do { 需执行的代码 } while (变量<=结束值)
<html> <body> <script> var i=0 do { document.write("The number is " + i) document.write("<br />") i=i+1 } while (i<0) </script> </body> </html>
The number is 0
The above is the detailed content of Introduction to loop knowledge in JavaScript (code examples). For more information, please follow other related articles on the PHP Chinese website!