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 中的(条件)运算符?
基础教程推荐
- 动态更新多个选择框 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01