JavaScript 三元运算符

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

什么是三元运算符?

三元运算符会评估一个条件,并根据该条件执行一段代码。

其语法为

condition ? expression1 : expression2

三元运算符会评估测试条件。

  • 如果条件为 true,则执行表达式1
  • 如果条件为 false,则执行表达式2

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


让我们编写一个程序,根据获得的标记来确定学生在考试中是否及格。

示例:JavaScript 三元运算符

// program to check pass or fail

let marks = prompt('Enter your marks :');

// check the condition
let result = (marks >= 40) ? 'pass' : 'fail';

console.log(`You ${result} the exam.`);

输出 1

Enter your marks: 78
You pass the exam.

假设用户输入 78。然后会检查条件 marks >= 40,该条件评估为 true。因此,第一个表达式 pass 被赋给 result 变量。

输出 2

Enter your marks: 35
You fail the exam.

假设用户输入 35。然后条件 marks >= 40 评估为 false。因此,第二个表达式 fail 被赋给 result 变量。


使用三元运算符代替 if...else

在 JavaScript 中,三元运算符可以用来替代某些类型的 if..else 语句。例如,

您可以将此代码替换为

// check the age to determine the eligibility to vote
let age = 15;
let result;

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 = 15;
let result =
    (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 number is positive, negative or zero
let a = 3;
let result = (a >= 0) ? (a == 0 ? "zero" : "positive") : "negative";
console.log(`The number is ${result}.`);

输出

The number is positive.

 

注意:应尽量避免使用嵌套三元运算符,因为它们会使您的代码难以阅读。

视频:JavaScript 三元运算符

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

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

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

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