1.目的:了解while循環的使用方法。
2.代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<!--
以下是while 循環語句:
1. while 循環:會在指定條件為真時循環執行代碼塊。
2. do/while 循環:是 while 循環的變體。該循環會在檢查條件是否為真之前執行一次代碼塊,然後如果條件為真的話,就會重複這個循環
-->
<!-- 範例一:while循環(循環代碼5次) -->
<p>範例一:while循環(循環代碼5次)</p>
<button οnclick="fun1()">點選按鈕</button>
<p id="demo1"></p>
<!-- 範例二:do/while循環 -->
<p>範例二:do/while循環(循環代碼5次)</p>
<button οnclick="fun2()">點選按鈕</button>
<p id="demo2"></p>
<script>
//範例一:while循環(循環代碼5次)
function fun1()
{
var x="",i=0;
while (i<5){
x=x + "該數字為 " + i + "<br>";
i++;
}
document.getElementById("demo1").innerHTML=x;
}
//範例二:do/while循環(循環代碼5次)
function fun2()
{
var x="",i=0;
do{
x=x + "該數字為 " + i + "<br>";
i++;
}
while (i<5)
document.getElementById("demo2").innerHTML=x;
}
</script>
</body>
</html>
3.結果: