can I use `else if` with a ternary operator?

后端 未结 2 969
一个人的身影
一个人的身影 2021-02-14 16:00

Can I only use if and else in a statement in ternary operator syntax or can I also somehow include an else if?

example:

         


        
相关标签:
2条回答
  • 2021-02-14 17:02

    Unlike an if with optional else or optional else if branches, a ternary operator has two and only two branches.

    It's actually a part of the name. Where + in a + b is a binary operator, that is it has two operands, ? has three, as in a ? b : c, and is termed ternary because of that. Technically there could be other ternary operators beyond ? but in most languages they don't exist, so it is generally understood that the name "ternary" means the ? operator.

    You can have else if like functionality if you sub-branch the second clause:

    a ? b : (c ? d : e)
    

    This is usually a bad idea as ternary operations can be messy to start with and layering like this is usually an express train to unmaintainable code.

    It is much better to write:

    if (a) {
      b
    }
    else if (c) {
    {
      d
    }
    else {
      e
    }
    

    This is more verbose, but abundantly clear.

    If you use ternaries too agressively you'll end up with code like:

    a()?c?d?e:f:g:h?i(j?k:l?m:n):o
    

    Where it's anyone's guess what's going on in there.

    0 讨论(0)
  • 2021-02-14 17:06

    You could stack multiple ternaries:

    var x = (y) ? 1 : ( (z) ? 2 : 0 );
    
    0 讨论(0)
提交回复
热议问题