Ternary operation in CoffeeScript
我需要将值设置为
用咖啡描述做这个最短的方法是什么?
例如,我在javascript中就是这样做的:
1 2 | a = true ? 5 : 10 # => a = 5 a = false ? 5 : 10 # => a = 10 |
由于所有内容都是一个表达式,因此会产生一个值,所以您只需使用
1 2 | a = if true then 5 else 10 a = if false then 5 else 10 |
您可以在这里看到更多关于表达式示例的信息。
1 2 | a = if true then 5 else 10 a = if false then 5 else 10 |
参见文档。
在几乎任何一种语言中,这都是可行的:
1 2 | a = true && 5 || 10 a = false && 5 || 10 |
CoffeeScript不支持javascript三元运算符。以下是咖啡描述作者的原因:
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 haveif/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:
1
2
3
4
5
6 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/coffeeesccript/issues/11 issuecomment-97802
如果它主要是真正的用法,也可以用两个语句来写:
1 2 | a = 5 a = 10 if false |
如果您需要更多的可能性,也可以使用switch语句:
1 2 3 | a = switch x when true then 5 when false then 10 |
使用布尔值可能会过大,但我发现它非常可读。
多行版本(例如,如果需要在每行后添加注释):
1 2 3 | a = if b # a depends on b then 5 # b is true else 10 # b is false |
您仍然可以使用类似的语法
1 | a = true then 5 else 10 |
更清楚了。