JavaScript whil...LOGIN

JavaScript while loop

JavaScript while loop

As long as the specified condition is true, the loop can continue to execute the code block.

while loop

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

Syntax

while (condition)
{
Code to be executed
}

Example

Loop in this example Will continue to run as long as variable i is less than 5:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</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>
Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </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>
submitReset Code
ChapterCourseware