TypeScript 三元运算符

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


在某些情况下,可以使用三元运算符来替代 if..else 语句。在学习三元运算符之前,请务必查看 TypeScript if...else 教程


什么是三元运算符?

三元运算符 ?: 是一个条件运算符,它根据条件表达式,对两个表达式中的一个(truefalse)进行求值。

这是一个三元运算符的简单示例。您可以阅读本教程的其余部分以了解更多信息。

示例

let age: number = 36;

// Check if the person is an adult
let result: string = (age >= 18) ? "Adult" : "Not Adult";

console.log(result);

// Output: Adult

在此,三元运算符检查 age 是否大于或等于 18。如果是,则将 "Adult" 赋给 result 变量。否则,将 "Not Adult" 赋给它。


TypeScript 三元运算符的语法

TypeScript 中三元运算符的语法是

condition ? expression1 : expression2

三元运算符对测试条件进行求值。如果 condition

  • true - 执行 expression1
  • false - 执行 expression2

三元运算符需要 **三个** 操作数,因此得名三元运算符。它也称为 **条件运算符**。


示例:TypeScript 三元运算符

让我们编写一个程序,根据学生获得的分数来确定他们是及格还是不及格。

// Program to check pass or fail

// prompt() returns either string or null
let userInput: string | null = prompt("Enter your marks: ");

// Type Narrowing: check if the input is valid
// String is valid input, null is invalid
if (typeof userInput === "string") {
    
    // Convert input to number
    let marks = Number(userInput);
    
    // Check the condition
    let result: string = (marks >= 40) ? "passed" : "failed";

    console.log(`You ${result} the exam.`);
}
else {
    console.log("Invalid input!");
}

输出 1

Enter your marks: 78
You passed the exam.

假设用户输入 78。那么条件 marks >= 40true

因此,第一个表达式 "passed" 被赋给 result 变量。

输出 2

Enter your marks: 35
You failed the exam.

假设用户输入 35。那么条件 marks >= 40 的求值结果为 false

因此,第二个表达式 "failed" 被赋给 result 变量。


三元运算符与 if...else

在 TypeScript 中,三元运算符和 if...else 语句的作用相似:根据特定条件有条件地执行代码。

但是,它们在 **语法** 和 **用例** 上有所不同。

三元运算符非常适合简洁的条件赋值或内联表达式。

另一方面,if...else 语句允许使用多个条件和代码块,使其更适合复杂的决策场景。

三元运算符可以用来替代某些类型的 if..else 语句。

例如,您可以将此代码替换为

// Check the age to determine the eligibility to vote
let age: number = 15;
let result: string;

if (age >= 18) {
    result = "You are eligible to vote.";
}
else {
    result = "You are not eligible to vote yet.";
}

console.log(result);

替换为

// Ternary operator to check the eligibility to vote
let age: number = 15;

let result: string = (age >= 18)
    ? "You are eligible to vote."
    : "You are not eligible to vote yet";

console.log(result);

两个程序的输出将相同。

输出

You are not eligible to vote yet.

嵌套的三元运算符

您还可以将一个三元运算符嵌套在另一个三元运算符中作为表达式。例如,

// Program to check if the number is positive, negative, or zero
let a: number = 3;
let result: string = (a >= 0) ? (a == 0 ? "zero" : "positive") : "negative";
console.log(`The number is ${result}.`);

输出

The number is positive.

注意:嵌套的三元运算符可能难以阅读。仅在逻辑简单且包含范围有限时使用它们。


另请阅读

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

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

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

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