語法:
switch(n) { case 1: 執行代碼塊 1 break; case 2: 執行代碼塊 2 break; default: n 與 case 1 和 case 2 不同時執行的代碼 }
工作原理:首先設置表達式 n(通常是一個變量)。隨后表達式的值會與結構中的每個 case 的值做比較。如果存在匹配,則與該 case 關聯的代碼塊會被執行。請使用 break 來阻止代碼自動地向下一個 case 運行。
實例:
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"; }
結果:
Looking forward to the Weekend
特殊寫法:
<script> switch ("香蕉") { case "香蕉": case "蘋果": case "葡萄": alert("你喜歡吃水果"); break; default: alert("你不喜歡水果嗎?"); } </script>