switch 陳述句來選擇要執行的多個代碼塊之一,switch 不能處理大于小于的
語法
switch(n) { case 1: 執行代碼塊 1 break; case 2: 執行代碼塊 2 break; default: 與 case 1 和 case 2 不同時執行的代碼 }
作業原理:首先設定運算式 n(通常是一個變數),隨后運算式的值會與結構中的每個 case 的值做比較,如果存在匹配,則與該 case 關聯的代碼塊會被執行,請使用 break 來阻止代碼自動地向下一個 case 運行,
注意,如果沒有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("星期一");
}
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前邊的代碼都沒有執行,到第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 的一個用法
當不同的條件產生同一個動作的時候,用法比較簡單
switch (i) { case 1: case 2: case 3: case 4: case 5: { document.write("作業");break; } case 6: case 7: { document.write("休息"); } }

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/177316.html
標籤:JavaScript
上一篇:記錄百度富文本踩過的一些坑
下一篇:js筆記之switch-case
