How do you use the ? : (conditional) operator in JavaScript?(你如何使用?: JavaScript 中的(条件)运算符?)
问题描述
简单来说,?:
(条件,三元")运算符是什么?如何使用它?
In simple words, what is the ?:
(conditional, "ternary") operator and how can I use it?
推荐答案
这是 if-else 语句的单行简写.它被称为条件运算符.1
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
这是一个可以使用条件运算符缩短的代码示例:
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
这可以用 ?:
缩短,如下所示:
This can be shortened with the ?:
like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
像所有表达式一样,条件运算符也可以用作具有副作用的独立语句,尽管这是 不寻常在缩小之外:
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
他们甚至可以被锁住:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
不过要小心,否则你会得到这样的复杂代码:
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
<小时>
1 通常称为三元运算符",但实际上它只是a三元运算符[接受三个操作数的运算符].不过,它是 JavaScript 目前唯一拥有的.
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
这篇关于你如何使用?: JavaScript 中的(条件)运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何使用?: JavaScript 中的(条件)运算符?


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01