js基礎⑤

來源:互聯網
上載者:User

標籤:一個   color   else   比較   bsp   自動   運算式   變數   工作原理   

條件陳述式、迴圈語句

一、if·

1、if

文法:

if (條件)  {  只有當條件為 true 時執行的代碼  }

2、if else

文法:

if (條件)  {  當條件為 true 時執行的代碼  }else  {  當條件不為 true 時執行的代碼  }

3、if elseif else

文法:

if (條件 1)  {  當條件 1 為 true 時執行的代碼  }else if (條件 2)  {  當條件 2 為 true 時執行的代碼  }else  {  當條件 1 和 條件 2 都不為 true 時執行的代碼  }

ps:else if可使用多次,最後的else語句不能再判斷條件了。

 

二、switch

文法:

switch(n){case 1:  執行代碼塊 1  break;case 2:  執行代碼塊 2  break;default:  n 與 case 1 和 case 2 不同時執行的代碼}

工作原理:首先設定運算式 n(通常是一個變數)。隨後運算式的值會與結構中的每個 case 的值做比較。如果存在匹配,則與該 case 關聯的代碼塊會被執行。請使用 break 來阻止代碼自動地向下一個 case 運行。

default關鍵詞:位於最後,當前面的所有條件(case)不匹配時,執行default後的語句

var day=new Date().getDay();switch (day){case 6:  x="Today it‘s Saturday";  break;case 0:  x="Today it‘s Sunday";  break;default:  x="Looking forward to the Weekend";}

 

三、for

文法:

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

語句 1 在迴圈(代碼塊)開始前執行


 

語句 2 定義運行迴圈(代碼塊)的條件


 

語句 3 在迴圈(代碼塊)已被執行之後執行

ps:語句1,2,3都是可省略的

 

省略時的文法:

//省略語句1:var i=2,len=cars.length;for (; i<len; i++){document.write(cars[i] + "<br>");}
//省略語句2for (var i=0,len=cars.length; ; i++){document.write(cars[i] + "<br>");break}//若省略語句2,這時預設為True,會導致無限迴圈,從而瀏覽器奔潰,務必在合適的位置加上break
//省略語句3var i=0,len=cars.length;for (; i<len; ){document.write(cars[i] + "<br>");i++;}

 

四、for in

建立:

<script>function myFunction(){var x;var txt="";var person={fname:"Bill",lname:"Gates",age:56}; for (x in person){txt=txt + person[x]+‘<br>‘;}document.getElementById("demo").innerHTML=txt;}</script>//結果:BillGates56

 

五、while

文法:

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

ps:同樣注意無限迴圈導致瀏覽器奔潰

 

六、do while

文法:

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

ps:與while幾乎一樣,唯一的區別是do while先執行語句,再判斷,所以至少會執行一次。同樣注意無限迴圈導致瀏覽器奔潰。

 

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.