JavaScript 三元条件运算符
本教程将介绍如何在 JavaScript 中使用 ?:
条件运算符。
if ... else
语句仅在满足特定条件时帮助我们执行特定代码块。条件运算符,也称为三元运算符,是 if ... else
语句的单行简写。它有助于编写干净简洁的代码。它是唯一一个需要 3 个操作数的 JavaScript 运算符:要计算的条件,如果条件为 true
时要执行的表达式,以及如果条件为 false
时要执行的表达式。因为它需要 3 个操作数,所以它的名字是三元运算符。
condition ? expression1 : expression2
三元运算符首先评估给定的 condition
。条件与 expression1
之间用 ?
分隔并且 expression2
与 expression1
由 :
分隔。如果 condition
为真,则条件运算符执行 expression1
,否则执行 expression2
。
示例:JavaScript 三元条件运算符
var age = 18;
var canVote;
if (age >= 18) {
canVote = 'yes';
} else {
canVote = 'no';
}
上面的示例显示了使用传统的 if ... else
语句执行的条件语句。
var age = 18;
var canVote = age >= 18 ? 'yes' : 'no';
我们已经使用三元运算符重写了上面的代码。
示例:JavaScript 嵌套三元运算符
与 if ... else
语句一样,我们也可以使用嵌套的三元运算符来执行多个条件检查。
var carSpeed = 90;
var warning =
speed >= 100 ? 'Way Too Fast!!' : (speed >= 80 ? 'Fast!!' : 'Nice :)');
console.log(warning);
在上面的代码中,我们根据汽车速度为汽车生成警告。首先,我们检查 carSpeed
是否超过 100,如果条件满足,我们会生成一个警告说 Way Too Fast!!
。否则,我们嵌套了第二个表达式,检查 carSpeed
是否大于 80 并根据评估显示 Fast
/ Nice
。
示例:JavaScript 三元运算符中的多项操作
我们可以在一个三元运算符中运行多个操作,就像 if ... else
语句一样。
let isStudent = true;
let primeVideo = 12;
isStudent ?
(primeVideo = primeVideo / 2, alert('Enjoy your student discount')) :
(alert('You have to pay full price'));
在上面的代码中,我们执行了两个操作而不是一个,将 primeVideo
的值更改为其一半并提醒用户。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。