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

发布于 2024-11-14 00:01:14 字数 58 浏览 1 评论 0原文

什么是 ?: (问号和冒号运算符,又名条件或“三元”)运算符以及如何使用它?

What is the ?: (question mark and colon operator aka. conditional or "ternary") operator and how can I use it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

梦断已成空 2024-11-21 00:01:14

这是 if-else 语句的单行简写。它称为条件运算符。1

下面是可以使用条件运算符缩短的代码示例:

var userType;
if (userIsYoungerThan18) {
  userType = "Minor";
} else {
  userType = "Adult";
}

if (userIsYoungerThan21) {
  serveDrink("Grape Juice");
} else {
  serveDrink("Wine");
}

可以使用 ?: 缩短代码,如下所示:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";

serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

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

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

它们甚至可以链接起来:

serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');

但是要小心,否则你最终会得到像这样的复杂代码:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;

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

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();

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;

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.

厌味 2024-11-21 00:01:14

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

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


而不是:

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

您可以使用:

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

这是 PHP 速记三元运算符 ?: 的 Javascript 等效项

甚至:

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

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

I want to add some 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.


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 ?:

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.

孤者何惧 2024-11-21 00:01:14

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

示例

?: 运算符可以用作
if...else 语句的快捷方式。
它通常用作
更大的表达式,其中 if...else
声明会很尴尬。为了
示例:

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

该示例创建一个字符串
包含“晚上好”。如果是的话
下午 6 点后。使用的等效代码
if...else 语句看起来像
如下:

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

来自 MSDN JS 文档

基本上它是一个简写的条件语句。

另请参阅:

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:

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:

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

From MSDN JS documentation.

Basically it's a shorthand conditional statement.

Also see:

Spring初心 2024-11-21 00:01:14

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

如果您在 JavaScript 中看到更多有趣的符号,您应该首先尝试查找 JavaScript 的运算符: Mozilla Developer中心运营商名单。您可能遇到的一个例外是 $ 符号

要回答您的问题,请用条件运算符替换简单的 if 语句。最好举个例子:

var insurancePremium = age > 21 ? 100 : 200;

而不是:

var insurancePremium;

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

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

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

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

var insurancePremium = age > 21 ? 100 : 200;

Instead of:

var insurancePremium;

if (age > 21) {
    insurancePremium = 100;
} else {
    insurancePremium = 200;
}
稍尽春風 2024-11-21 00:01:14

大多数答案都是正确的,但我想补充一点。 三元运算符是右关联的,这意味着它可以通过以下方式链接 if … else-if … else-if … else

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

相当于:

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

更多详细信息位于此处

Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way 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

盛夏尉蓝 2024-11-21 00:01:14
z = (x == y ? 1 : 2);

相当于

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

除了,当然,它更短。

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

is equivalent to

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

except, of course, it's shorter.

红颜悴 2024-11-21 00:01:14

三元运算符

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

示例:

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

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

示例

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

这个三元运算符与 C 编程语言中的类似。

Ternary Operator

Commonly we have conditional statements in 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.

Example:

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

This Ternary operator is Similar in C programming language.

‖放下 2024-11-21 00:01:14

它被称为三元运算符

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

It is called the ternary operator

tmp = (foo==1 ? true : false);
混吃等死 2024-11-21 00:01:14

嘿伙计,记住 js 的工作原理是评估 true 或 false,对吧?

让我们采用三元运算符:

questionAnswered ? "Awesome!" : "damn" ;

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

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

否则( : )你会得到“damn”;

希望这对朋友有帮助:)

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

let's take a ternary operator :

questionAnswered ? "Awesome!" : "damn" ;

First, js checks whether questionAnswered is true or false.

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

else ( : ) you will get "damn";

Hope this helps friend :)

天冷不及心凉 2024-11-21 00:01:14

三元表达式在 JS 中非常有用,尤其是 React。这是对所提供的许多好的、详细的答案的简化答案。

condition ? expressionIfTrue : expressionIfFalse

expressionIfTrue 视为呈现 true 的 OG if 语句;
expressionIfFalse 视为 else 语句。

示例:

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

检查 x 的值,如果 true,则返回第一个 y=(value),如果 false,则返回冒号后的第二个 y=(value)。

Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.

condition ? expressionIfTrue : expressionIfFalse

Think of expressionIfTrue as the OG if statement rendering true;
think of expressionIfFalse as the else statement.

Example:

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

this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.

网名女生简单气质 2024-11-21 00:01:14
x = 9
y = 8

一元

++x
--x

二进制

z = x + y

三元

2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";
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";
少年亿悲伤 2024-11-21 00:01:14

这是一个 if 语句,全部在一行中。

所以

var x=1;
(x == 1) ? y="true" : y="false";
alert(y);

要求值的表达式在( )中,

如果匹配true,则执行后面的代码?

如果匹配false,则执行后面的代码:

It's an if statement all on one line.

So

var x=1;
(x == 1) ? y="true" : y="false";
alert(y);

The expression to be evaluated is in the ( )

If it matches true, execute the code after the ?

If it matches false, execute the code after the :

听风吹 2024-11-21 00:01:14

条件(三元)运算符是唯一的 JavaScript 运算符
这需要三个操作数。该运算符经常用作
if 语句的快捷方式。

condition ? expr1 : expr2 

如果条件为真,则该运算符返回 expr1 的值;
否则,返回 expr2 的值。

function fact(n) {
  if (n > 1) {
    return n * fact(n-1);
  } else {
    return 1;
  }
  // we can replace the above code in a single line of code as below
  //return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));

如需更多说明,请阅读 MDN 文档链接

The conditional (ternary) operator is the only JavaScript operator
that takes three operands. This operator is frequently used as a
shortcut for the if statement.

condition ? expr1 : expr2 

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

function fact(n) {
  if (n > 1) {
    return n * fact(n-1);
  } else {
    return 1;
  }
  // we can replace the above code in a single line of code as below
  //return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));

For more clarification please read MDN document link

策马西风 2024-11-21 00:01:14

我们可以使用 Jquery 以及长度,如下例所示:

假设我们有 GuarantorName 文本框,它具有值并且想要获取名字和姓氏 - 它可能为空。
所以rathar比

        var gnamesplit = $("#txtGuarantorName").val().split(" ");
        var gLastName = "";
        var gFirstName = "";
        if(gnamesplit.length > 0 ){
           gLastName  = gnamesplit[0];        
        }
        if(gnamesplit.length > 1 ){
           gFirstName = gnamesplit[1];        
        }

我们可以使用下面的代码与Jquery以最少的代码

    

    var gnamesplit = $("#txtGuarantorName").val().split(" ");
    var gLastName = gnamesplit.length > 0  ? gnamesplit[0] : "";
    var gFirstName =  gnamesplit.length > 1  ? gnamesplit[1] : "";
    $("#txtLastName").val(gLastName);
    $("#txtFirstName").val(gFirstName);
    
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div >
  Guarantor Name: <input type="text" id="txtGuarantorName" value="ASP.NET Core"  /><br/>
  <br/>
  <br/>
  
  First Name: <input type="text" id="txtLastName" value="ASP.NET Core"  />
  Last Name: <input type="text" id="txtFirstName" value="ASP.NET Core"  />
</div>

We can use with Jquery as well as length as below example :

Suppose we have GuarantorName textbox which has value and want to get firstname and lastname- it may be null.
So rathar than

        var gnamesplit = $("#txtGuarantorName").val().split(" ");
        var gLastName = "";
        var gFirstName = "";
        if(gnamesplit.length > 0 ){
           gLastName  = gnamesplit[0];        
        }
        if(gnamesplit.length > 1 ){
           gFirstName = gnamesplit[1];        
        }

We can use below code with Jquery with minimum code

    

    var gnamesplit = $("#txtGuarantorName").val().split(" ");
    var gLastName = gnamesplit.length > 0  ? gnamesplit[0] : "";
    var gFirstName =  gnamesplit.length > 1  ? gnamesplit[1] : "";
    $("#txtLastName").val(gLastName);
    $("#txtFirstName").val(gFirstName);
    
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div >
  Guarantor Name: <input type="text" id="txtGuarantorName" value="ASP.NET Core"  /><br/>
  <br/>
  <br/>
  
  First Name: <input type="text" id="txtLastName" value="ASP.NET Core"  />
  Last Name: <input type="text" id="txtFirstName" value="ASP.NET Core"  />
</div>

柏拉图鍀咏恒 2024-11-21 00:01:14

利用三元运算符,编写一个程序,如果数字是偶数,则打印“偶数”;如果数字是奇数,则打印“奇数”。

let a = 13;
let b = a%2!==0 ? "is Odd number" : "is Even number";
// let b = a%2==0 ? "is Even number" : "is Odd number";
console.log(a+" "+b);

输出:13是奇数

By using Ternary operator, write a program to Print “Even Number”, if the number is even or Print “Odd Number”, if the number is odd.

let a = 13;
let b = a%2!==0 ? "is Odd number" : "is Even number";
// let b = a%2==0 ? "is Even number" : "is Odd number";
console.log(a+" "+b);

Output : 13 is Odd number

伤痕我心 2024-11-21 00:01:14

它称为三元运算符。有关更多信息,这是我回答的另一个问题:

如何编写不带“else”的 IF else 语句

It's called the ternary operator. For some more info, here's another question I answered regarding this:

How to write an IF else statement without 'else'

风蛊 2024-11-21 00:01:14

这可能不是最优雅的方法。但对于不熟悉三元运算符的人来说,这可能很有用。我个人的偏好是使用 1 行后备而不是条件块。

  // var firstName = 'John'; // Undefined
  var lastName = 'Doe';

  // if lastName or firstName is undefined, false, null or empty => fallback to empty string
  lastName = lastName || '';
  firstName = firstName || '';

  var displayName = '';

  // if lastName (or firstName) is undefined, false, null or empty
  // displayName equals 'John' OR 'Doe'

  // if lastName and firstName are not empty
  // a space is inserted between the names
  displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;


  // if display name is undefined, false, null or empty => fallback to 'Unnamed'
  displayName = displayName || 'Unnamed';

  console.log(displayName);

三元运算符

This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.

  // var firstName = 'John'; // Undefined
  var lastName = 'Doe';

  // if lastName or firstName is undefined, false, null or empty => fallback to empty string
  lastName = lastName || '';
  firstName = firstName || '';

  var displayName = '';

  // if lastName (or firstName) is undefined, false, null or empty
  // displayName equals 'John' OR 'Doe'

  // if lastName and firstName are not empty
  // a space is inserted between the names
  displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;


  // if display name is undefined, false, null or empty => fallback to 'Unnamed'
  displayName = displayName || 'Unnamed';

  console.log(displayName);

Ternary Operator

丿*梦醉红颜 2024-11-21 00:01:14

如果您在 javascript 中有一个条件检查实例函数。使用三元运算符很容易。只需一行即可实现。
例如:

    private module : string ='';
    private page:boolean = false;
    async mounted(){
     if(this.module=== 'Main')
    {
    this.page = true;}
    else{
    this.page = false;
    }
}

像这样具有一个条件的函数可以写如下。

this.page = this.module=== 'Main' ?true:false;

条件?如果为真:如果为假

If you have one condition check instance function in javascript. it's easy to use ternary operator. which will only need one single line to implement.
Ex:

    private module : string ='';
    private page:boolean = false;
    async mounted(){
     if(this.module=== 'Main')
    {
    this.page = true;}
    else{
    this.page = false;
    }
}

a function like this with one condition can be written as follow.

this.page = this.module=== 'Main' ?true:false;

condition ? if True : if False

佼人 2024-11-21 00:01:14

三元运算符只是编写 if else 条件的一种简单方法。它在ReactJS中被广泛使用。

例如:

const x = 'foo';

// Instead of if else use this
x === 'foo' ? alert('True') : alert('False');

// Output
// alert box will prompt 'True'

Ternary operator is just a simple way to write if else condition. It is widely used in ReactJS.

For Example:

const x = 'foo';

// Instead of if else use this
x === 'foo' ? alert('True') : alert('False');

// Output
// alert box will prompt 'True'

如歌彻婉言 2024-11-21 00:01:14
 (sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";

 sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"
 (sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";

 sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文