CoffeeScript中的三元操作

本文翻译自:Ternary operation in CoffeeScript

I need to set value to a that depends on a condition. 我需要设置值, a是取决于一个条件。

What is the shortest way to do this with CoffeeScript? 使用CoffeeScript执行此操作的最短方法是什么?

Eg this is how I'd do it in JavaScript: 这就是我在JavaScript中的表现:

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

#1楼

参考:https://stackoom.com/question/gZSS/CoffeeScript中的三元操作


#2楼

Since everything is an expression, and thus results in a value, you can just use if/else . 由于一切都是表达式,因此产生一个值,你可以使用if/else

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

You can see more about expression examples here . 您可以在此处查看更多关于表达式示例


#3楼

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

See documentation . 文档


#4楼

In almost any language this should work instead: 在几乎任何语言中,这应该起作用:

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

#5楼

You may also write it in two statements if it mostly is true use: 如果它主要是真的使用,你也可以用两个语句写它:

a = 5
a = 10 if false

Or use a switch statement if you need more possibilities: 如果您需要更多可能性,请使用switch语句:

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

With a boolean it may be oversized but i find it very readable. 使用布尔值可能超大但我发现它非常易读。


#6楼

Coffeescript doesn't support javascript ternary operator. Coffeescript 不支持 javascript三元运算符。 Here is the reason from the coffeescript author : 以下是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. 我喜欢三元运算符和下一个运算符一样多(实际上可能更多),但语法并不能使它们变得更好 - 它们很棒,因为它们可以将if / else放在一行上作为一个表达。

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). 结果是相同的,我更倾向于if/elses总是看起来一样(并且总是被编译成表达式)。

So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause: 因此,在CoffeeScript中,即使是多行ifs也会在适当的时候编译为三元组,if if语句也没有else子句:

 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". 所以,谢谢你的建议,但我关闭这张票是“wontfix”。

Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802 请参考github问题: https//github.com/jashkenas/coffeescript/issues/11#issuecomment-97802

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值