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

2018-12-31 01:40发布

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

16条回答
冷夜・残月
2楼-- · 2018-12-31 02:04
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";
查看更多
深知你不懂我心
3楼-- · 2018-12-31 02:05

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

查看更多
不流泪的眼
4楼-- · 2018-12-31 02:06

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.

查看更多
何处买醉
5楼-- · 2018-12-31 02:07

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.

查看更多
妖精总统
6楼-- · 2018-12-31 02:14

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 :

查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 02:14

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.

ex: 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. Happy coding.

查看更多
登录 后发表回答