我需要根据条件将值设置为a。

用CoffeeScript做这件事的最短方法是什么?

例如,这是我在JavaScript中如何做到的:

a = true  ? 5 : 10  # => a = 5
a = false ? 5 : 10  # => a = 10

当前回答

Coffeescript不支持javascript三元运算符。 以下是coffeescript作者给出的原因:

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".

请参考github的问题:https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802

其他回答

如果是真的,你也可以把它写成两种说法:

a = 5
a = 10 if false

如果你需要更多的可能性,可以使用switch语句:

a = switch x
  when true then 5
  when false then 10

与布尔它可能是超大的,但我发现它非常可读。

因为所有内容都是表达式,因此会产生一个值,所以可以使用if/else。

a = if true then 5 else 10
a = if false then 5 else 10

你可以在这里看到更多关于表达式的例子。

a = if true then 5 else 10
a = if false then 5 else 10 

见文档。

Coffeescript不支持javascript三元运算符。 以下是coffeescript作者给出的原因:

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".

请参考github的问题:https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802

几乎在任何语言中,这都是可行的:

a = true  && 5 || 10
a = false && 5 || 10