TypeScript Switch语句
TypeScript Switch语句从多个条件中执行一个语句。它根据其值评估一个表达式,该值可以是Boolean、number、byte、short、int、long、枚举类型、字符串等。Switch语句对应每个值有一个代码块。当匹配成功时,将执行相应的代码块。Switch语句类似于if-else-if梯形语句。
在Switch语句中必须记住以下几点:
- Switch语句内可以有N个案例。
 - Case值必须是唯一的。
 - Case值必须是常量。
 - 每个Case语句都在代码末尾有一个break语句。break语句是可选的。
 - Switch语句有一个默认块,写在最后。默认语句是可选的。
 
语法
switch(expression){
case expression1:
    //code to be executed;
    break;  //optional
case expression2:
    //code to be executed;
    break;  //optional
    ........
default:
    //when no case is matched, this block will be executed;
    break;  //optional
}
Switch语句包含以下内容。在switch语句内可以有任意数量的case。
Case: case后面应该紧跟一个常量,然后是一个分号。它不能接受另一个变量或表达式。
Break: break应该写在block的末尾,在执行完case block后退出switch语句。如果我们不写break,则执行将继续与后续case block匹配的值。
Default: default块应该写在switch语句的结尾。只有当没有case匹配时才会执行。

示例
let a = 3;
let b = 2;
switch (a+b){
    case 1: {
        console.log("a+b is 1.");
        break;
    }
    case 2: {
        console.log("a+b is 5.");
        break;
    }
    case 3: {
        console.log("a+b is 6.");
        break;
    }
    default: {
        console.log("a+b is 5.");
        break;
    }
}
输出:

使用字符串的Switch case
let grade: string = "A";
switch (grade)
{ 
    case'A+':
      console.log("Marks >= 90"+"\n"+"Excellent");
      break;
    case'A':
      console.log("Marks [ >= 80 and <90 ]"+"\n"+"Good");
      break;
    case'B+':
      console.log("Marks [ >= 70 and <80 ]"+"\n"+"Above Average");
      break;
    case'B':
      console.log("Marks [ >= 60 and <70 ]"+"\n"+"Average");
      break;
    case'C':
      console.log("Marks < 60"+"\n"+"Below Average");
      break;
    default:
        console.log("Invalid Grade.");
}
在这个例子中,我们有一个字符串变量grade。switch语句评估grade变量值,并与case子句匹配,然后执行其相关语句。
输出:

使用枚举的Switch Case
在TypeScript中,我们可以使用枚举的switch case,方法如下。
示例
enum Direction {
    East,
    West,
    North,
    South    
};
var dir: Direction = Direction.North;
function getDirection() {
    switch (dir) {
        case Direction.North: console.log('You are in North Direction');
            break;
        case Direction.East: console.log('You are in East Direction');
            break;
        case Direction.South: console.log('You are in South Direction');
            break;
        case Direction.West: console.log('You are in West Direction');
            break;
    }
}
getDirection();
输出:

TypeScript Switch语句是Fall-through的。
TypeScript switch语句是fall-through的。这意味着如果没有break语句,则它会执行第一个匹配case后面的所有语句。
示例
let number = 20;  
switch(number)
{  
    //switch cases without break statements  
    case 10: console.log("10");  
    case 20: console.log("20");  
    case 30: console.log("30");  
    default: console.log("Not in 10, 20 or 30");
}
输出:

极客教程