你如何使用?: JavaScript 中的(条件)运算符? [英] How do you use the ? : (conditional) operator in JavaScript?

查看:19
本文介绍了你如何使用?: 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 中的(条件)运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆