JavaScript -- 迴圈語句

來源:互聯網
上載者:User

標籤:onclick   log   asc   oop   bsp   title   工具   html   for 迴圈   

JavaScript 支援不同類型的迴圈:

  • for - 迴圈代碼塊一定的次數
  • for/in - 迴圈遍曆對象的屬性
  • while - 當指定的條件為 true 時迴圈指定的代碼塊
  • do/while - 同樣當指定的條件為 true 時迴圈指定的代碼塊
For 迴圈

for 迴圈是您在希望建立迴圈時常會用到的工具。

文法:

for (語句 1; 語句 2; 語句 3){    被執行的代碼塊}

 

while 迴圈

while 迴圈會在指定條件為真時迴圈執行代碼塊。

文法:

while (條件){    需要執行的代碼}
do/while 迴圈

do/while 迴圈是 while 迴圈的變體。該迴圈會在檢查條件是否為真之前執行一次代碼塊,然後如果條件為真的話,就會重複這個迴圈。

文法:

do{    需要執行的代碼}while (條件);

demo:

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <title>迴圈語句</title>    </head>    <body>        <script type="text/javascript" src="test.js" ></script>        <button onclick="loop()">迴圈語句</button>    </body></html>

js裡面的迴圈語句邏輯代碼:

/** * 迴圈語句 */function loop(){        document.write("----------for迴圈遍曆-----------" + "<br>");            cars = ["BMW", "Volvo", "Saab", "Ford"];            for (var i = 0; i < cars.length; i++) {                document.write(cars[i] + "<br>");            }            document.write("---------------------" + "<br>");            var i = 0,                len = cars.length;            for (; i < len;) {                document.write(cars[i] + "<br>");                i++;            }            document.write("----------for/in 語句迴圈遍曆對象的屬性-----------" + "<br>");            var x;            var txt = "";            var person = {                fname: "Bill",                lname: "Gates",                age: 56            };            //通過for in 進行對象遍曆            for (x in person) {                //字串拼接,通過+                txt = txt + person[x];            }            document.write(txt + "<br>");            document.write("----------while迴圈語句----------" + "<br>");            var x = "",                i = 0;            while (i < 5) {                x = x + "該數字為 " + i + "<br>";                i++;            }            document.write(x + "<br>");            document.write("----------do while迴圈語句----------" + "<br>");            var x = "",                i = 0;            do {                x = x + "the number is " + i + "<br>";                i++;            }            while (i < 5)            document.write(x + "<br>");}

 

JavaScript -- 迴圈語句

聯繫我們

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