Js 迴圈結構

來源:互聯網
上載者:User

標籤:結束   程式碼片段   style   基本   round   meta   blog   javascrip   html   

迴圈結構:程式反覆執行同一套程式碼片段。遇到結束條件,會結束執行。

沒有迴圈結束條件,永遠迴圈執行——死迴圈

迴圈三要素:

1.迴圈條件:迴圈繼續執行的條件。 一旦迴圈條件不滿足,迴圈立刻退出~

2.迴圈變數:使用者條件中做判斷的變數

迴圈變數都會向迴圈退出的趨勢變化(不滿足迴圈條件的趨勢) ------迴圈計數器

3.迴圈體:每次迴圈要做的事情

while迴圈:當滿足條件時,就繼續迴圈做。。。事

var 迴圈變數;

while(迴圈條件){

  迴圈體;

  迭代變化迴圈變數;

}

<!DOCTYPE html><html>  <head>    <meta charset="utf-8" />    <title></title>  </head>  <body>    <script type="text/javascript">      //申明迴圈變數      var round = 0;      //先判斷條件      while(round<3){            if(round==2){          console.log("暈");          break;        }        round++;        console.log(round);      }      console.log("停車");    </script>  </body></html>

 

break:退出結構

while中何時用break:迴圈條件不滿足之前,希望強行退出迴圈。

如何使用break? 可以放在任何需要退出迴圈的位置。

執行個體:

<!DOCTYPE html><html>    <head>        <meta charset="utf-8" />        <title></title>    </head>    <body>        <script type="text/javascript">            var n=10;            //迴圈條件:input!=n&&input!=‘exit‘            //迴圈變數:input            var input=-1;            while(input!=n&&input!=‘exit‘){                input=prompt("你猜:");                if(input!=""){  //防屌絲 不輸入                    if(input=="exit"){                        console.log("放棄了");                        break;                    }else{                        input=parseInt(input);                        if(n>input){                            alert("輸入小了");                        }else if(n<input){                            alert("輸入大了");                        }else{                            alert("猜對了");                        }                    }                }                            }        </script>    </body></html>

while 中用的迴圈變數基本都是全域變數中的。

隨機數:Math.random():0<=n<1

任意min--max之間區隨機數

 

公式:parseInt((Math.random()*(max-min+1)+min))

例如:60 -- 100

   0<=n<1

    0<=n*41<41

    60<=parseInt(n*41+60)<=100

 

Js 迴圈結構

聯繫我們

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