for
將一段代碼迴圈執行指定的次數
while
當指定的條件為 true 時迴圈執行代碼
for 迴圈
在指令碼的運行次數已確定的情況下使用 for 迴圈。
文法:
for (變數=開始值;變數<=結束值;變數=變數+步進值)
{
需執行的代碼
}
執行個體:
解釋:下面的例子定義了一個迴圈程式,這個程式中 i 的起始值為 0。每執行一次迴圈,i 的值就會累加一次 1,迴圈會一直運行下去,直到 i 等於 10 為止。
注釋:步進值可以為負。如果步進值為負,需要調整 for 聲明中的比較子。
| 代碼如下 |
複製代碼 |
|
<html>
<body>
<script type="text/javascript">
var i=0for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
} </script>
</body>
</html>結果:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10 |
while 迴圈用於在指定條件為 true 時迴圈執行代碼。
文法:
while (變數<=結束值)
{
需執行的代碼
}
注意:除了<=,還可以使用其他的比較子。
執行個體:
解釋:下面的例子定義了一個迴圈程式,這個迴圈程式的參數 i 的起始值為 0。該程式會反覆運行,直到 i 大於 10 為止。i 的步進值為 1。
| 代碼如下 |
複製代碼 |
|
<html>
<body>
<script type="text/javascript">
var i=0while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
} </script>
</body>
</html>
結果:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10 |
do...while 迴圈
do...while 迴圈是 while 迴圈的變種。該迴圈程式在初次運行時會首先執行一遍其中的代碼,然後當指定的條件為 true 時,它會繼續這個迴圈。所以可以這麼說,do...while 迴圈為執行至少一遍其中的代碼,即使條件為 false,因為其中的代碼執行後才會進行條件驗證。
文法:
do {
需執行的代碼
}while
(變數<=結束值)執行個體:
| 代碼如下 |
複製代碼 |
|
<html>
<body>
<script type="text/javascript">
var i=0do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0) </script>
</body>
</html>
結果:
The number is 0 |
如何退出迴圈呢,在js中我們可以使用 break 和 continue來退出迴圈
有兩種特殊的語句可用在迴圈內部:break 和 continue。
Break
break 命令可以終止迴圈的運行,然後繼續執行迴圈之後的代碼(如果迴圈之後有代碼的話)。
執行個體:
| 代碼如下 |
複製代碼 |
|
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break} document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
結果:
The number is 0
The number is 1
The number is 2 |
Continue
continue 命令會終止當前的迴圈,然後從下一個值繼續運行。
執行個體:
| 代碼如下 |
複製代碼 |
|
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue} document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
結果:
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10 |