JavaScript while循环
程序员文章站
2024-03-23 21:44:34
...
当while 的条件为真时执行代码
语法:
while (条件){
// 代码块
}
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="myFunction()">click</button>
<p id="demo"></p>
<script>
function myFunction(){
var num = 0,mes = "";
while (num<5){
mes =mes + "The number:" + num + "<br>";
num++;
}
document.getElementById("demo").innerHTML=mes;
}
</script>
</body>
</html>
结果:
do/while循环,这个与while循环的差别的地方就是会先执行一次代码块,再去判断条件是否为真
语法:
do {
// 代码块
}
while (条件);
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="myFunction()">click</button>
<p id="demo"></p>
<script>
function myFunction(){
var num = 5,mes = "";
do {
mes = mes + "The number is: " + num + "<br>";
}
while (num<5);
document.getElementById("demo").innerHTML=mes;
}
</script>
</body>
</html>
结果: