我需要根据条件将值设置为a。
用CoffeeScript做这件事的最短方法是什么?
例如,这是我在JavaScript中如何做到的:
a = true ? 5 : 10 # => a = 5
a = false ? 5 : 10 # => a = 10
我需要根据条件将值设置为a。
用CoffeeScript做这件事的最短方法是什么?
例如,这是我在JavaScript中如何做到的:
a = true ? 5 : 10 # => a = 5
a = false ? 5 : 10 # => a = 10
当前回答
a = if true then 5 else 10
a = if false then 5 else 10
见文档。
其他回答
CoffeeScript没有三元操作符。医生是这么说的。
你仍然可以使用这样的语法
a = true then 5 else 10
这样就清楚多了。
如果是真的,你也可以把它写成两种说法:
a = 5
a = 10 if false
如果你需要更多的可能性,可以使用switch语句:
a = switch x
when true then 5
when false then 10
与布尔它可能是超大的,但我发现它非常可读。
类似于quotesBro的答案,但没有then关键字。下面是一个使用普通多行if语句的版本。对我来说,这是一个很好的格式。
考虑一下这个正常的if语句
if true
# do stuff
else
# do stuff
然后使用它来赋值(同样,没有Then关键字)
value = if true
5
else
10
value = if false
5
else
10
这编译成javascript作为一个规则的三元
value = true ? 5 : 10;
value = false ? 5 : 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 = if b # a depends on b
then 5 # b is true
else 10 # b is false