JavaScript中for迴圈的使用詳解_基礎知識

來源:互聯網
上載者:User

 我們已經看到,while迴圈有不同變種。本章將介紹另一種流行的迴圈叫做for迴圈。
for 迴圈

for迴圈是迴圈最緊湊的形式,並包含有以下三個重要部分組成:

  1.     迴圈初始化計數器的初始值。初始化語句執行迴圈開始之前。
  2.     測試語句,將測試如果給定的條件是真還是假。如果條件為真,那麼將要執行的迴圈中給定的代碼,否則迴圈會退出來。
  3.     迴圈語句,可以增加或減少計數器。

可以把所有的三個部分中的一行用分號隔開。
文法

for (initialization; test condition; iteration statement){   Statement(s) to be executed if test condition is true}

例子:

下面的例子說明一個基本的for迴圈:

<script type="text/javascript"><!--var count;document.write("Starting Loop" + "<br />");for(count = 0; count < 10; count++){ document.write("Current Count : " + count ); document.write("<br />");}document.write("Loop stopped!");//--></script>

這將產生以下結果,它類似於while迴圈:

Starting LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped! 

聯繫我們

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