JavaScript whil...LOGIN

JavaScript while loop

while loop

The while loop loops through a block of code while a specified condition is true.

Syntax

while (condition)
{
Code to be executed
}

Example

The loop in this example will continue to run as long as variable i is less than 10:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
while (i<5){
x=x + "该数字为 " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

Note : If you forget to increment the value of the variable used in the condition, the loop will never end. This may cause the browser to crash.

Run the program and try it


##do/while loop

The do/while loop is a variation of the while loop body. The loop executes the block of code once before checking whether the condition is true, and then repeats the loop if the condition is true.

Syntax

do

{
Code to be executed
}
while (condition );

Example

The following example uses a do/while loop. The loop will execute at least once, and it will execute even if the condition is false, because the code block will execute before the condition is tested:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
do{
x=x + "该数字为 " + i + "<br>";
   i++;
}
while (i<5)  
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

Run the program to try it



Next Section

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>点击下面的按钮,只要 i 小于 10 就一直循环代码块。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction(){ var x="",i=0; while (i<10){ x=x + "该数字为 " + i + "<br>"; i++; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
submitReset Code
ChapterCourseware