TypeScript 条件语句

TypeScript 条件语句

编程语言中的决策制定类似于现实生活中的决策制定。在编程语言中,程序员使用决策制定来指定一个或多个条件,这些条件将由程序评估。决策制定总是返回布尔结果true或false。

在TypeScript中有各种类型的决策制定:

  • if语句
  • if-else语句
  • if-else-if梯度
  • 嵌套if语句

if语句

这是一种简单的决策制定形式。它决定语句是否会被执行,即它检查条件并在给定条件满足时返回true。

语法

if(condition) {
     // code to be executed
}

TypeScript 条件语句

示例

let a = 10, b = 20;
if (a < b) 
{
    console.log('a is less than b.');
}

输出:

a is less than b.

if-else语句

if语句只在条件为真时返回结果。但是如果我们希望在条件为假时返回一些东西,那么我们需要使用if-else语句。if-else语句测试条件。如果条件为真,则执行if代码块;如果条件为假,则执行else代码块。

语法

if(condition) {
  // code to be executed
} else {
   // code to be executed
}

TypeScript 条件语句

示例

let n = 10
if (n > 0) { 
   console.log("The input value is positive Number: " +n);
} else {
    console.log("The input value is negative Number: " +n);
}

输出:

The input value is positive Number: 10

if-else-if梯子

用户可以在多个选项之间做出决策。它以自上而下的方式开始执行。当条件为true时,它执行相应的语句,并绕过其余的条件。如果它找不到任何条件为true的情况,它将返回最后的else语句。

语法

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}

TypeScript 条件语句

示例

let marks = 95;
if(marks<50){
    console.log("fail");
}
else if(marks>=50 && marks<60){
    console.log("D grade");
}
else if(marks>=60 && marks<70){
    console.log("C grade");
}
else if(marks>=70 && marks<80){
    console.log("B grade");
}
else if(marks>=80 && marks<90){
    console.log("A grade");
}else if(marks>=90 && marks<100){
    console.log("A+ grade");
}else{
    console.log("Invalid!");
}

输出:

A+ grade

嵌套if语句

在这里,if语句针对另一个if语句。嵌套if语句意味着if语句在另一个if或else语句的主体内部。

语法

if(condition1) {
    //Nested if else inside the body of "if"
    if(condition2) {
       //Code inside the body of nested "if"
    }
    else {
       //Code inside the body of nested "else"
    }
}
else {
    //Code inside the body of "else."
}

TypeScript 条件语句

示例

let n1 = 10, n2 = 22, n3 = 25  
if (n1 >= n2) {  
    if (n1 >= n3) {  
        console.log("The largest number is: " +n1)  
    }  
    else {  
        console.log("The largest number is: " +n3)  
    }  
}  
else {  
    if (n2 >= n3) {  
        console.log("The largest number is: " +n2)  
    }  
    else {  
        console.log("The largest number is: " +n3)  
    }  
}  

输出:

The largest number is: 25

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程