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

查看:111
本文介绍了你怎么用的? :JavaScript中的(条件)运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以用简单的话向我解释什么是?:(有条件的,三元)运算符以及如何使用它?

Can someone please explain to me in simple words what is the ?: (conditional, "ternary") operator and how to 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:

if(userIsYoungerThan21) {
  serveGrapeJuice();
}
else {
  serveWine();
}

这可以用缩短?:喜欢这样:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

在Javascript中,条件运算符可以计算表达式,而不仅仅是语句:

In Javascript conditional operator can evaluate to an expression, not just a statement:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

它们甚至可以被链接:

userIsYoungerThan4 ? serveMilk() : userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

但要小心,否则你最终会得到如下错综复杂的代码:

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 通常称为三元运算符,但实际上它只是一个三元运算符[一个接受三个运算符的运算符]。不过,它是目前唯一拥有的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天全站免登陆