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 01:52

It is called the ternary operator

tmp = (foo==1 ? true : false);
查看更多
零度萤火
3楼-- · 2018-12-31 01:54

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

查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 01:57

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'

查看更多
骚的不知所云
5楼-- · 2018-12-31 02:00

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

查看更多
唯独是你
6楼-- · 2018-12-31 02:01
 (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>"
查看更多
唯独是你
7楼-- · 2018-12-31 02:03
z = (x == y ? 1 : 2);

is equivalent to

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

except, of course, it's shorter.

查看更多
登录 后发表回答