018_switch语句
生活随笔
收集整理的這篇文章主要介紹了
018_switch语句
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. switch語句
1.1. switch語句是if語句的兄弟語句。
1.2. switch語句的語法:
switch (expression)case value: statement;break;case value: statement;break;case value: statement;break;case value: statement;break; ...case value: statement;break;default: statement;1.3. 每個情況(case)都是表示"如果expression等于value, 就執行statement”。
1.4. 關鍵字break會使代碼跳出switch語句。如果沒有關鍵字break, 代碼執行就會繼續進入下一個case。
1.5. 關鍵字default說明了表達式的結果不等于任何一種情況時的操作(事實上, 它相對于else從句)。
2. switch語句作用
2.1. if語句
if (i == 20)alert("20"); else if (i == 30)alert("30"); else if (i == 40)alert("40"); elsealert("other");2.2. 上面的if語句等價的switch語句是這樣的, 我們用switch代替if語句:
switch (i) {case 20: alert("20");break;case 30: alert("30");break;case 40: alert("40");break;default: alert("other"); }3. 例子
3.1. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>switch語句</title></head><body><script type="text/javascript">var i = 20;switch (i) {case 20: document.write("i = " + i);break;case 30: document.write("i = " + i);break;case 40: document.write("i = " + i);break;default: document.write("unknow i value");}</script></body> </html>3.2. 效果圖
總結
以上是生活随笔為你收集整理的018_switch语句的全部內容,希望文章能夠幫你解決所遇到的問題。