javascript shorthand if statement, without the else portion

后端 未结 7 1541
孤街浪徒
孤街浪徒 2020-12-01 07:52

So I\'m using a shorthand javascript if/else statement (I read somewhere they\'re called Ternary statements?)

this.dragHandle.hasClas

7条回答
  •  感动是毒
    2020-12-01 07:58

    Don't think of it like a control-block (ie: an if-else or a switch). It's not really meant for running code inside of it.

    You can. It just gets very ugly, very fast, which defeats the purpose.

    What you really want to use it for is ASSIGNING VALUES.

    Taking your initial example and turning it on its head a little, you get:

    direction = (this.dragHandle.hasClass("handle-low")) ? "left" : "right";
    

    See. Now what I've done is I've taken something that would have required an if/else or a switch, which would have been used to assign to that one value, and I've cleaned it up nice and pretty.

    You can even do an else-if type of ternary:

    y = (x === 2) ? 1 : (x === 3) ? 2 : (x === 4) ? 7 : 1000;
    

    You can also use it to fire code, if you'd like, but it gets really difficult after a while, to know what's going where (see the previous example to see how even assignment can start looking weird at a glance)...

    ((this.dragHandle.hasClass("...")) ? fireMe(something) : noMe(somethingElse));
    

    ...this will typically work.

    But it's not really any prettier or more-useful than an if or a branching, immediately-invoking function (and non-JS programmers, or untrained JS programmers are going to crap themselves trying to maintain your code).

提交回复
热议问题