TypeScript if...else 语句

注意: 如果您是 TypeScript 新手,请先查看我们的 TypeScript 入门 教程。


TypeScript 中的 if...else 语句用于根据条件执行/跳过一段代码。

这是一个 if...else 语句的简单示例。您可以阅读本教程的其余部分以了解更多信息。

示例

let quantity: number = 35;

// Check if quantity is a positive number
if (quantity > 0) {
    console.log("Positive number");
}
// Else, check if quantity is negative
else if (quantity < 0) {
    console.log("Negative number");
}
// If both conditions fail, quantity is 0
else {
    console.log("Zero");
}

// Output: Positive number

在上面的示例中,程序显示

  • 如果 quantity 大于 0,则显示 Positive number
  • 如果 quantity 小于 0,则显示 Negative number
  • 如果没有任何条件匹配,则显示 Zero

TypeScript if 语句

我们使用 if 关键字根据某些特定条件执行代码。

if 语句的语法是

if (condition) {
    // Block of code
}

if 关键字检查括号 () 中的 condition。如果 condition 的计算结果为

  • true - 将执行 { } 中的代码。
  • false - 将跳过 { } 中的代码。

注意: { } 中的代码也称为 if 语句的主体。

Working of if statement in TypeScript
if 语句的工作原理

示例 1:TypeScript if 语句

// Program to check if the student passed

let score: number = 96;

// Check if score is greater than or equal to 40
if (score >= 40) {
    // The body of the if statement
    console.log("You passed the examination.");
}

console.log("Program executed!");

输出

You passed the examination.
Program executed!

在上面的程序中,条件 score >= 40 的计算结果为 true,因为 score96。因此,将执行 if 语句的主体。

如果分数低于 40(例如 35),则不会执行 if 语句的主体。

最后,由于 console.log("Program executed!"); 位于 if 语句主体之外,因此无论 if 语句的结果如何,它都会被执行。


TypeScript else 语句

当前面 if 语句中的条件计算为 false 时,else 关键字将执行一段代码。

注意: else 语句应始终跟在 if 语句之后。换句话说,ifelse 语句是单个条件结构的一部分。

if...else 语句的语法是

if (condition) {
    // Block of code to execute if the condition is true
}
else {
    // Block of code to execute if the condition is false
}

if...else 语句通过两种方式检查 condition 并执行代码:

  • 如果 conditiontrue,则执行 if 中的代码。并且,将跳过 else 中的代码。
  • 如果 conditionfalse,则跳过 if 中的代码。而是执行 else 中的代码。
Working of if-else statement in TypeScript
if...else 语句的工作原理

示例 2:TypeScript if…else 语句

// Program to check if the student passed or failed

let score: number = 35;

// Check if score is greater than or equal to 40
if (score >= 40) {
    // The body of the if statement
    console.log("You passed the examination.");
}
else {
    // The body of the else statement
    console.log("You failed the examination.");
}

console.log("Program executed!");

输出

You failed the examination.
Program executed!

由于 score35,因此 if 条件 (score >= 40) 的计算结果为 false

因此,将跳过 if 中的代码。而将执行 else 中的代码。

什么时候可以省略 if…else 语句中的 { }?

当我们要执行单行代码时,可以省略 if…else 语句中的 { }。例如,

let score: number = 35;

if (score >= 40)
    console.log("You passed the examination.");
else
    console.log("You failed the examination.");

// Output: You failed the examination.

TypeScript else if 语句

如果初始 if 语句为 false,则使用 else if 关键字来检查其他条件。

else if 语句的语法是

// Check for first condition
if (condition1) {
    // if body
}

// Check for second condition
else if (condition2){
    // else if body
}

// If no condition matches
else {
    // else body
}

这里

  1. 首先,检查 if 语句中的条件。如果条件计算为 true,则执行 if 的主体,并跳过其余部分。
  2. 否则,检查 else if 语句中的条件。如果为 true,则执行其主体并跳过其余部分。
  3. 最后,如果没有条件匹配,则执行 else 中的代码块。
Working of if-else ladder statement in TypeScript
if...else if...else 语句的工作原理

示例 3:TypeScript if...else if 语句

let score: number = 59;

// Check if score is 80 or above
if (score >= 80) {
    console.log("Excellent!");
}
// Else, check if score 40 or above
else if (score >= 40) {
    console.log("Average");
}
// If both conditions fail, you fail the exam
else {
    console.log("Failure!");
}

输出

Average

在这里,if 条件为 false,因为 score59。但是,else if 条件满足,因此程序打印 Average

如何使用多个 else if 语句?

我们可以根据需要多次使用 else if 关键字。例如,

let score: number = 85;

// Condition for passing with second division
if (score >= 40 && score < 60) {
    console.log("Second division");
}
// Condition for passing with first division
else if (score >= 60 && score < 80) {
    console.log("First division");
}
// Condition for passing with distinction
else if (score >= 80 && score <= 100) {
    console.log("Distinction");
}
// Condition for failing the exam
else if (score > 0 && score < 40) {
    console.log("You failed the examination.");
}
// If all conditions fail, the score is invalid
else {
    console.log("Invalid score!");
}

// Output: Distinction

在上面的示例中,我们使用了三个 else if 语句。

第二个 else if 语句被执行,因为它的条件得到了满足,而 if 和第一个 else if 语句的条件未得到满足。


嵌套 if...else 语句

当我们使用嵌套在另一个 if...else 语句中的 if...else 语句时,我们就创建了一个嵌套 if...else 语句。例如,

let score: number = 60;

// Outer if...else statement
// Student passed if score 40 or above
// Otherwise, student failed

if (score >= 40) {

    // Inner if...else statement
    // Distinction if score is 80 or above

    if (score >= 80) {
        console.log("Distinction");
    }
    else {
        console.log("Passed");
    }
}

else {
    console.log("Failed");
}

// Output: Passed

外部 if...else 语句

在上面的示例中,外部 if 条件使用条件 score >= 40 检查学生是及格还是不及格。如果计算结果为 false,则外部 else 语句将打印 "Failed"

另一方面,如果 score >= 40 的计算结果为 true,程序将进入内部 if...else 语句。

内部 if...else 语句

内部 if 条件使用条件 score >= 80 检查学生是否以优异成绩及格。

如果 score >= 80 的计算结果为 true,则内部 if 语句将打印 "Distinction"

否则,内部 else 语句将打印 "Passed"

注意: 为了保持代码的可读性并简化调试,请避免将多个 if...else 语句相互嵌套。


更多关于 TypeScript if...else 语句

什么时候可以使用三元运算符而不是 if...else 语句?

如果我们的操作非常简单,我们可以使用三元运算符 ?: 代替 if...else 语句。例如,

let score: number = 40;
let result;

if (score >= 40) 
    result = "pass"
else
    result = "fail"

console.log(result);

// Output: pass

可以写成

let score: number = 40;

let result = (score >= 40) ? "pass" : "fail";

console.log(result);

// Output: pass
什么时候可以用 switch 语句替换 if...else 语句?

当我们需要处理大量条件时,我们可以用 switch 语句替换我们的 if...else 语句。

例如,

let score: string = "C";

// Using if else for many conditions
// First condition
if (score === "A") {
    console.log("Excellent!");
}
// Second condition
else if (score === "B") {
    console.log("Good!");
}
// Third condition
else if (score === "C") {
    console.log("Average");
}
// Fourth condition
else if (score === "D") {
    console.log("Bad");
}
// Otherwise, execute else block
else {
    console.log("Fail");
}

// Output: Average

在上面的示例中,我们使用了 if...else 来评估五个条件,包括 else 块。

现在,让我们使用 switch 语句来实现相同的目的。

let score: string = "C";

// using switch...case
switch (score) {
    // First condition
    case "A":
        console.log("Excellent!");
        break;
    // Second condition
    case "B":
        console.log("Good!");
        break;
    // Third condition
    case "C":
        console.log("Average");
        break;
    // Fourth condition
    case "D":
        console.log("Bad");
        break;
    default:
        console.log("Fail");
}

// Output: Average

如您所见,switch 语句使我们的代码更具可读性和可维护性。

此外,与冗长的 if...else 语句链相比,switch 的运行速度更快。

如何在单个 if 语句中添加多个条件?

我们可以在 if 语句中使用逻辑运算符,如 &&|| 来添加多个条件。例如,

let age: number = 35;
let salary: number = 6000;

// Combine two conditions using the "and" operator &&
if (age >= 30 && salary >= 5000) {
    console.log("Eligible for premium membership.");
}
else {
    console.log("Not eligible for premium membership.");
}

// Output: Eligible for premium membership.

在这里,我们在 if 语句中使用了逻辑运算符 && 来添加两个条件。这两个条件是:

  • age >= 30
  • salary >= 5000

由于 && 运算符,必须使两个条件都为 true 才能执行 if 块。

可以使用 if...else 语句来检查用户输入吗?

是的,您可以在 if...else 语句中使用用户输入。只需确保已将输入转换为合适的类型即可。例如,

// Get user input from prompt(), which returns either string or null data
const userInput: string | null = prompt("Enter your exam score:");

// Check if user input is null
if (userInput === null) {
    console.log("Null input given!");
}
// Else, convert input to integer and check condition
else {
    let score: number = parseInt(userInput);

    // Check if the user passed or failed
    if (score >= 40)
        console.log("pass");
    else
        console.log("fail");
}

在这里,我们使用了 prompt() 函数来获取用户输入。如果用户提供输入数据,prompt() 将其作为字符串返回。

但是,如果用户按下 Cancel 按钮,prompt() 将返回 null。因此,我们需要检查此条件。

一旦我们确定输入不是 null,我们就可以使用 parseInt() 函数将输入转换为整数,然后检查用户是及格还是不及格。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战