简体   繁体   中英

Javascript Ternary Logic Issue

I recently came across a ternary logic statement in this form:

condition, condition ? condition ? expr1 : expr2 : expr3

I am not sure how to interpret this. I am not seeing anything on the web. Anybody got any info on this.

condition, condition ? condition ? expr1 : expr2 : expr3

First you have a comma operator. This evaluates as the right hand side. So the first condition does nothing.


condition ? condition ? expr1 : expr2 : expr3

Then you just have two ternary expressions

It is the same as:

condition ? (condition ? expr1 : expr2) : expr3

So if the first condition is false, you get expr3.

Otherwise, the second condition picks between expr1 and expr2.


Never write code like this! Concisenes is only a virtue to the point where it makes it hard to understand what code means.

Let's try:)

condition1, condition2 ? condition3 ? expr1 : expr2 : expr3

condition1 don't parse. Let's use 'return' for example.

if( condition2 ){
  if(condition3){ 
      return exp1;
  } else { 
      return expr2;
  }
} else {
  return expr3;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM