Ternary operation in CoffeeScript

前端 未结 7 1601
生来不讨喜
生来不讨喜 2020-12-04 06:56

I need to set value to a that depends on a condition.

What is the shortest way to do this with CoffeeScript?

E.g. this is how I\'d do it in Java

7条回答
  •  时光取名叫无心
    2020-12-04 07:24

    Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:

    I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.

    Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have if/elses always look the same (and always be compiled into an expression).

    So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:

    if sunny   
      go_outside() 
    else   
      read_a_book().
    
    if sunny then go_outside() else read_a_book()
    

    Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".

    Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802

提交回复
热议问题