switch/case 語句
switch/case 語句
在做大量的選擇判斷的時候,如果依然使用 if/else 結(jié)構(gòu),那么代碼有可能會變得很凌亂,于是我們采用 switch/case 結(jié)構(gòu):
switch(k) { case k1: 執(zhí)行代碼塊 1 ; break; case k2: 執(zhí)行代碼塊 2 ; break; default: 默認(rèn)執(zhí)行(k 值沒有在 case 中找到匹配時); }
語法說明:
Switch必須賦初始值,值與每個case值匹配。滿足執(zhí)行該 case 后的所有語句,并用break語句來阻止運(yùn)行下一個case。如所有case值都不匹配,執(zhí)行default后的語句。
假設(shè)評價學(xué)生的考試成績,10分滿分制,我們按照每一分一個等級將成績分等,并根據(jù)成績的等級做出不同的評價。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>switch</title> <script type="text/JavaScript"> var myweek =1;//myweek表示星期幾變量 switch(myweek) { case 1: case 2: document.write("學(xué)習(xí)理念知識"); break; case 3: case 4: document.write("到企業(yè)實踐"); break; case 5: document.write("總結(jié)經(jīng)驗"); break; case 6: case 7: document.write("周六、日休息和娛樂"); break; default: window.alert('輸入有誤'); } </script> </head> <body> </body> </html>
<html> <body> <p>點(diǎn)擊下面的按鈕,會顯示出基于今日日期的消息:</p> <button onclick="myFunction()">點(diǎn)擊這里</button> <p id="demo"></p> <script> function myFunction() { var x; var d=new Date().getDay(); switch (d) { case 6: x="Today it's Saturday"; break; case 0: x="Today it's Sunday"; break; default: x="Looking forward to the Weekend"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>