Javascript基礎教程之while語句,javascript基礎教程

來源:互聯網
上載者:User

Javascript基礎教程之while語句,javascript基礎教程

迴圈語句的作用是反覆的執行同一段代碼,儘管分幾種不同的類型,但其原理幾乎相同;只要給定的條件滿足,包含在迴圈體內的語句會不斷執行,一旦條件不再滿足則終止。

while迴圈是前測試迴圈,這意味著是否終止的條件判斷是在執行代碼之前,因此,迴圈的主體可能根本不執行。其文法如下:

while(expression) statement

當expression為ture時,程式會不斷執行statement語句,直到expression為false時。

兩個案例

複製代碼 代碼如下:
 <script type="text/javascript">
    var i=iSum=0;
    while(i <= 100){
        iSum += i;
        i++;
     };
    document.write(iSum+"<br>"); //求100內數字相加和
     </script>
 <p>點擊下面的按鈕,只要 i 小於 5 就一直迴圈代碼塊。</p>
 <button onclick="myFunction()">點擊這裡</button>
 <p id="demo"></p>
 <script>
     function myFunction()
     {
         var x="",i=0;
         while (i<=10)
         {
             x=x + "The number is " + i + "<br>";
             i++;
         }
         document.getElementById("demo").innerHTML=x;
     }
 </script>

聯繫我們

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