JavaScript For While 迴圈使用方法詳解

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.