我需要根据条件将值设置为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
当前回答
类似于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 = true && 5 || 10
a = false && 5 || 10
a = if true then 5 else 10
a = if false then 5 else 10
见文档。
因为所有内容都是表达式,因此会产生一个值,所以可以使用if/else。
a = if true then 5 else 10
a = if false then 5 else 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;