JavaScript while 循环

JavaScript while 循环

只要指定条件为 true,循环就可以一直执行代码块。

while 循环

while 循环会在指定条件为真时循环执行代码块。

语法

while (条件)
  {
  需要执行的代码
  }

实例

本例中的循环将继续运行,只要变量 i 小于 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>
继续学习
||
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!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>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
提交重置代码
图片放大关闭