📜  TypeScript切换语句

📅  最后修改于: 2021-01-11 12:32:54             🧑  作者: Mango

TypeScript切换语句

TypeScript switch语句从多个条件中执行一个语句。它根据其值来计算表达式,该值可以是布尔值,数字,字节,short,int,long,enum类型, 字符串等。switch语句具有一个与每个值相对应的代码块。找到匹配项后,将执行相应的块。 switch语句的工作方式类似于if-else-if阶梯语句。

在switch语句中必须记住以下几点:

  • switch语句中可以有N个案例。
  • 大小写值必须唯一。
  • 大小写值必须恒定。
  • 每个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块之后,应将中断写在块的末尾,以便从switch语句中得出。如果我们不写中断,则执行将继续执行与后续case块匹配的值。

默认值:默认块应写入switch语句的末尾。在没有大小写匹配的情况下执行。

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;
    }
}

输出:

带弦开关盒

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语句评估等级变量值并与case子句匹配,然后执行其关联的语句。

输出:

带枚举的开关盒

在TypeScript中,我们可以通过以下方式在Enum中使用switch大小写。

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语句失败。

TypeScript switch语句是失败的。这意味着,如果不存在break语句,则它将在第一个匹配大小写之后执行所有语句。

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");
}

输出: