switch 語(yǔ)句來(lái)選擇要執行的多個(gè)代碼塊之一。switch 不能處理大于小于的
語(yǔ)法
switch(n){ case 1: 執行代碼塊 1 break; case 2: 執行代碼塊 2 break; default: 與 case 1 和 case 2 不同時(shí)執行的代碼}
工作原理:首先設置表達式 n(通常是一個(gè)變量)。隨后表達式的值會(huì )與結構中的每個(gè) case 的值做比較。如果存在匹配,則與該 case 關(guān)聯(lián)的代碼塊會(huì )被執行。請使用 break 來(lái)阻止代碼自動(dòng)地向下一個(gè) case 運行。
注意,如果沒(méi)有break 匹配上一條以后,下邊的條件不匹配,但是會(huì )執行代碼塊的
<!DOCTYPE html><html lange = "en"><head> <meta charset="UTF-8"> <title>js之switch </title></head><body> <h1>js之switch </h1> <script type="text/javascript"> var i = 4; switch (i) { case 1: { document.write("星期一"); } case 2: { document.write("星期二"); } case 3: { document.write("星期三"); } case 4: { document.write("星期四"); } case 5: { document.write("星期五"); } case 6: { document.write("星期六"); } case 7: { document.write("星期日"); } } </script></body>
結果如下
即4前邊的代碼都沒(méi)有執行,到第4條匹配以后,后續的不管是否匹配都執行都執行
加上break后
<!DOCTYPE html><html lange = "en"><head> <meta charset="UTF-8"> <title>js之switch </title></head><body> <h1>js之switch </h1> <script type="text/javascript"> var i = 4; switch (i) { case 1: { document.write("星期一");break; } case 2: { document.write("星期二");break; } case 3: { document.write("星期三");break; } case 4: { document.write("星期四");break; } case 5: { document.write("星期五");break; } case 6: { document.write("星期六");break; } case 7: { document.write("星期日"); } } </script></body>
運行結果如下
switch 的一個(gè)用法
當不同的條件產(chǎn)生同一個(gè)動(dòng)作的時(shí)候,用法比較簡(jiǎn)單
switch (i) { case 1: case 2: case 3: case 4: case 5: { document.write("工作");break; } case 6: case 7: { document.write("休息"); } }
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。