简体   繁体   中英

Javascript complex One-liner if statements

First time saw such ternary expressions:

var somevar = b1 ? b2 ? b3 : b4 : b5 ? b6 : b7 ? b8 : b9 ? b10 : b11

Having a hard time understanding and converting it to:

if (b1) {
} else if (bx) {
}

I've looked everywhere and can't seem to find the answer to this.

Just add parentheses.

var somevar = (b1 ? (b2 ? b3 : b4) : (b5 ? b6 : (b7 ? b8 : (b9 ? b10 : b11))))

Ie

if (b1) {
  if (b2) {
    b3
  } else {
    b4
  }
} else {
  if (b5) {
    b6
  } else {
    if (b7) {
      b8
    } else {
      if (b9) {
        b10
      } else {
        b11
      }
    }
  }
}

Or to make it shorter.

if (b1) {
  if (b2) {
    b3
  } else {
    b4
  }
} else if (b5) {
  b6
} else if (b7) {
  b8
} else if (b9) {
  b10
} else {
  b11
}

Start from the far right. whenever you find a ? b : c a ? b : c add parentheses around it.

For example:

 a ?  b ? c : d  : e

 a ? (b ? c : d) : e

(a ? (b ? c : d) : e)
Firstly convert it into parenthesis: 
(b1 ? 
     (b2 ? b3 :  b4 ) :   (b5 ? 
                               b6 : (b7 ? 
                                         b8 : (b9 ? b10 : b11) 
                                     )
                            )
  )

Then according to it use following code:

  var somevars;
  if(b1)
  {
    if(b2) somevars=b3
    else somevars=b4
  }
  else 
  {
    if(b5) 
       somevars=b6
    else 
    {
      if(b7) 
      {
        somevars=b8
      }
      else  
      {
        if(b9) somevars=b10
        else somevars=b11
      }
    }
  }

Clearly I would suggest torturing the person who wrote such code, but in lieu of that you could write this:

var somevar;

if (b1) {
    if (b2) {
        somevar = b3;
    } else {
        somevar = b4;
    }
} else {
    if (b5) {
        somevar = b6;
    } else {
        if (b7) {
            somevar = b8;
        } else {
            if (b9) {
                somevar = b10;
            } else {
                somevar = b11;
            }
        }
    }
}

Here is my solution:

if (b1) {
    if (b2) {
        b3
    } else {
        b4
    }
} else if (b5x) {
    b6
} else if (b7) {
    b8
} else if (b9) {
    b10
} else {
    b11
}

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