JavaScript 中的“?:”符号是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3322704/
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-10-25 00:51:23  来源:igfitidea点击:

What is "?:" notation in JavaScript?

javascriptsyntaxcoding-styleoperatorsnotation

提问by webdad3

I found this snippet of code in my travels in researching JSON:

我在研究 JSON 的旅途中发现了这段代码:

var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

I'm seeing more and more of the ?and :notation. I don't even know what it is called to look it up! Can anyone point me to a good resource for this? (btw, I know what !=means).

我看到越来越多的?:符号。我都不知道叫什么来查!任何人都可以为我指出一个很好的资源吗?(顺便说一句,我知道什么!=意思)。

回答by Matt Huggins

It's called a Conditional (ternary) Operator. It's essentially a condensed if-else.

它被称为条件(三元)运算符。它本质上是一个浓缩的 if-else。

So this:

所以这:

var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

...is the same as this:

...与此相同:

var array;
if (typeof objArray != 'object') {
    array = JSON.parse(objArray);
} else {
    array = objArray;
}

回答by Alexander Gessler

It's the ternary conditional operator -- basically,

这是三元条件运算符——基本上,

if (condition) {
   a = 4;
}
else {
   a = 5;
}

becomes

变成

a = condition ? 4 : 5;

回答by Gumbo

That's called the conditional operator:

这称为条件运算符

condition ? expr1 : expr2

If conditionis true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

condition ? expr1 : expr2

如果conditiontrue,运算符返回的值expr1;否则,它返回 的值expr2

回答by BerggreenDK

Just read it like this:

只需像这样阅读它:

result = (condition) ? (true value) : (false value);

place what ever you like in the 3 operators.

在 3 个操作员中放置您喜欢的任何内容。

As many has compared it to an IF.. THEN structure, so it is.

许多人将其与 IF.. THEN 结构进行了比较,因此确实如此。