Switch 語句

Switch 語句將表示式的值與 1 個或多個值進行比較,並根據該比較執行不同的程式碼段。

var value = 1;
switch (value) {
  case 1:
    console.log('I will always run');
    break;
  case 2:
    console.log('I will never run');
    break;
}

break 語句從 switch 語句中中斷並確保不再執行 switch 語句中的程式碼。這就是如何定義部分並允許使用者進行中斷的情況。

警告 :每個案例缺少 breakreturn 宣告意味著程式將繼續評估下一個案例,即使案例標準未得到滿足!

switch (value) {
  case 1:
    console.log('I will only run if value === 1');
    // Here, the code "falls through" and will run the code under case 2
  case 2:
    console.log('I will run if value === 1 or value === 2');
    break;
  case 3:
    console.log('I will only run if value === 3');
    break;
}

最後一個案例是 default 情況。如果沒有其他匹配,這個將執行。

var animal = 'Lion';
switch (animal) {
  case 'Dog':
    console.log('I will not run since animal !== "Dog"');
    break;
  case 'Cat':
    console.log('I will not run since animal !== "Cat"');
    break;
  default:
    console.log('I will run since animal does not match any other case');
}

應該注意,案例表達可以是任何型別的表達。這意味著你可以使用比較,函式呼叫等作為案例值。

function john() {
  return 'John';
}

function jacob() {
  return 'Jacob';
}

switch (name) {
  case john(): // Compare name with the return value of john() (name == "John")
    console.log('I will run if name === "John"');
    break;
  case 'Ja' + 'ne': // Concatenate the strings together then compare (name == "Jane")
    console.log('I will run if name === "Jane"');
    break;
  case john() + ' ' + jacob() + ' Jingleheimer Schmidt':
    console.log('His name is equal to name too!');
    break;
}

case 的多重包容性標準

由於 case 在沒有 breakreturn 語句的情況下掉頭,你可以使用它來建立多個包含標準:

var x = "c"
switch (x) {
   case "a":
   case "b":
   case "c":
      console.log("Either a, b, or c was selected.");
      break;
   case "d":
      console.log("Only d was selected.");
      break;
   default:
      console.log("No case was matched.");
      break;  // precautionary break if case order changes
}