如果 switch 的變數跟 case 一樣就會執行,如果沒有 break 會繼續執行下一個 case。
switch(x) {case'value1': // if (x === 'value1')... [break]case'value2': // if (x === 'value2')... [break]default:... [break]}
An example
let a =2+2;switch (a) {case3:alert( 'Too small' );break;case4:alert( 'Exactly!' );break;case5:alert( 'Too large' );break;default:alert( "I don't know such values" );}// can be expressionlet a ="1";let b =0;switch (+a) {case b +1:alert("this runs, because +a is 1, exactly equals b+1");break;default:alert("this doesn't run");}
Grouping of “case”
執行一樣的 code,可以寫成巢狀。
let a =2+2;switch (a) {case4:alert('Right!');break;case3: // (*) grouped two casescase5:alert('Wrong!');alert("Why don't you take a math class?");break;default:alert('The result is strange. Really.');}
Type matters
因為用 === 判斷 code 是否執行,所以值的類型很重要。
let arg =prompt("Enter a value?");switch (arg) {case'0':case'1':alert( 'One or zero' );break;case'2':alert( 'Two' );break;case3:alert( 'Never executes!' );break;default:alert( 'An unknown value' );}