Coffeescript 中等效的 Ruby .times [英] Equivalent Ruby .times in Coffeescript
本文介绍了Coffeescript 中等效的 Ruby .times的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与以下内容最简洁等效的 Coffeescript 是什么:
What is the most concise equivalent Coffeescript to the following:
# ruby
3.times { puts 'hi' }
?
我能想到的最好的是:
# coffeescript
for n in [1..3]
console.log 'hi'
推荐答案
console.log 'hi' for [1..3]
要正确处理0
:
console.log 'hi' for [1..n] if n
或者使用原型魔法:
Number::times = (fn) ->
do fn for [1..@valueOf()] if @valueOf()
return
3.times -> console.log 'hi'
请注意,不建议使用第二种方法,因为更改 Number
原型会产生全局影响.
Note that the second method isn't recommended because changing the Number
prototype has global effects.
根据@BrianGenisio 的评论更改(.prototype.
-> ::
)
编辑 2:固定处理 0,感谢@Brandon
这篇关于Coffeescript 中等效的 Ruby .times的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文