JavaScript For 迴圈_基礎知識

來源:互聯網
上載者:User
JavaScript中的迴圈用來將同一段代碼執行指定的次數(或者當指定的條件為true時)。
JavaScript 迴圈
在編寫代碼時,你常常希望反覆執行同一段代碼。我們可以使用迴圈來完成這個功能,這樣就用不著重複地寫若干行相同的代碼。
JavaScript有兩種不同種類的迴圈:
for 
將一段代碼迴圈執行指定的次數 
while 
當指定的條件為true時迴圈執行代碼 for 迴圈
在指令碼的運行次數已確定的情況下使用for迴圈。
文法:
複製代碼 代碼如下:

for (var=開始值;var<=結束值;var=var+步進值)  

    需執行的代碼 


執行個體:
解釋:下面的例子定義了一個迴圈程式,這個程式中i的起始值為0。每執行一次迴圈,i的值就會累加一次1,迴圈會一直運行下去,直到i等於10為止。
注意:步進值可以為負。如果步進值為負,需要調整for聲明中的比較子。
<html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { document.write("The number is " + i) document.write("") } </script> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

結果:
複製代碼 代碼如下:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.