你如何使用?:(条件)JavaScript 中的运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6259982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:59:36  来源:igfitidea点击:

How do you use the ? : (conditional) operator in JavaScript?

javascriptternary-operator

提问by muudless

Can someone please explain to me in simple words what is the ?:(conditional, "ternary") operator and how to use it?

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

回答by Peter Olson

This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

这是 if-else 语句的单行简写。它被称为条件运算符。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 unusualoutside of minification:

像所有表达式一样,条件运算符也可以用作具有副作用的独立语句,尽管这在缩小之外是不寻常的:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

They can even be chained:

它们甚至可以被链接起来:

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;


1Often called "the ternary operator," but in fact it's just aternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

1通常被称为“三元运算符”,但实际上它只是一个三元运算符[接受三个操作数的运算符]。不过,它是 JavaScript 目前唯一的一种。

回答by Jeffrey Roosendaal

I want to addsome to the given answers.

我想在给定的答案中添加一些内容。

In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.

如果您遇到(或想使用)三元在“如果设置了变量,则显示变量,否则...”之类的情况下,您可以使其更短,而无需 ternary



Instead of:

代替:

var welcomeMessage  = 'Hello ' + (username ? username : 'guest');

You can use:

您可以使用:

var welcomeMessage  = 'Hello ' + (username || 'guest');

This is Javascripts equivallent of PHP's shorthand ternary operator ?:

这是 PHP 的速记三元运算符的 Javascripts 等价物 ?:

Or even:

甚至:

var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');

It evaluates the variable, and if it's false or unset, it goes on to the next.

它评估变量,如果它为假或未设置,则继续下一个。

回答by Michael Robinson

It's called the 'ternary' or 'conditional' operator.

它被称为“三元”或“条件”运算符。

Example

例子

The ?: operator can be used as a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward. For example:

?: 运算符可用作 if...else 语句的快捷方式。它通常用作较大表达式的一部分,其中 if...else 语句会很笨拙。例如:

var now = new Date();
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");

The example creates a string containing "Good evening." if it is after 6pm. The equivalent code using an if...else statement would look as follows:

该示例创建了一个包含“晚安”的字符串。如果是下午6点以后。使用 if...else 语句的等效代码如下所示:

var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
   greeting += " evening.";
else
   greeting += " day.";

From MSDN JS documentation.

来自MSDN JS 文档

Basically it's a shorthand conditional statement.

基本上它是一个速记条件语句。

Also see:

另见:

回答by David Tang

It's a little hard to google when all you have are symbols ;) The terms to use are "javascript conditional operator".

当你只有符号时,用谷歌搜索有点困难;) 使用的术语是“javascript 条件运算符”。

If you see any more funny symbols in Javascript, you should try looking up Javascript's operators first: MDC's list of operators. The one exception you're likely to encounter is the $symbol.

如果您在 Javascript 中看到更多有趣的符号,您应该首先尝试查找 Javascript 的运算符:MDC 的运算符列表。您可能会遇到的一个例外是$符号

To answer your question, conditional operatorsreplace simple if statements. An example is best:

为了回答您的问题,条件运算符替换了简单的 if 语句。一个例子是最好的:

var insurancePremium = age > 21 ? 100 : 200;

Instead of:

代替:

var insurancePremium;

if (age > 21) {
    insurancePremium = 100;
} else {
    insurancePremium = 200;
}

回答by Ernest Friedman-Hill

z = (x == y ? 1 : 2);

is equivalent to

相当于

if (x == y)
    z = 1;
else
    z = 2;

except, of course, it's shorter.

除了,当然,它更短。

回答by Arif

Most of the answers are correct but I want to add little more. The ternary operatoris right-associative, which means it can be chainedin the following way if … else-if?… else-if … else:

大多数答案是正确的,但我想补充一点。该三元运算符是右结合的,这意味着它可以被链接以下列方式if … else-if?… else-if … else

function example() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

Equivalent to:

相当于:

function example() {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

More details is here

更多细节在这里

回答by Simplans

Ternary Operator

三元运算符

Commonly we have conditional statements in Javascript.

通常我们在 Javascript 中有条件语句。

Example:

例子:

if (true) {
    console.log(1)
} 
else {
    console.log(0)
}
# Answer
# 1

but it contain two or more lines and cannot assign to a variable. Javascript have a solution for this Problem Ternary Operator. Ternary Operator can write in one line and assign to a variable.

但它包含两行或更多行并且不能分配给变量。Javascript 有针对这个问题三元运算符的解决方案。三元运算符可以写在一行中并分配给变量。

Example:

例子:

var operator = true ? 1 : 0
console.log(operator)
# Answer
# 1

This Ternary operator is Similar in C programming language.

这个三元运算符在 C 编程语言中是相似的。

回答by eagle12

It is called the ternary operator

它被称为三元运算符

tmp = (foo==1 ? true : false);

回答by Guy Keren

Hey mate just remember js works by evaluating to either true or false, right?

嘿,伙计,请记住 js 通过评估 true 或 false 来工作,对吗?

let's take a ternary operator :

让我们拿一个三元运算符:

questionAnswered ? "Awesome!" : "damn" ;

First, js checks whether questionAnswered is trueor false.

首先,js 检查 questionAnswered 是true还是false

if true( ?) you will get "Awesome!"

如果 true( ?) 你会得到“真棒!”

else ( :) you will get "damn";

否则 ( :) 你会得到“该死的”;

Hope this helps friend :)

希望这对朋友有帮助:)

回答by Gajendra D Ambi

x = 9
y = 8

unary

一元

++x
--x

Binary

二进制

z = x + y

Ternary

三元

2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";