最简洁的咖啡脚本是什么
# ruby
3.times { puts 'hi' }
?
我能想到的最好的办法是:
# coffeescript
for n in [1..3]
console.log 'hi'
最简洁的咖啡脚本是什么
# 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
原型会产生全局影响.
Edit: Changed according to @BrianGenisio's comment (.prototype.
-> ::
)
Edit 2: fixed handling of 0, thanks @Brandon