siv*_*udh 41 ruby coffeescript
以下是最简洁的等效Coffeescript:
# ruby
3.times { puts 'hi' }
Run Code Online (Sandbox Code Playgroud)
?
我能想到的最好的是:
# coffeescript
for n in [1..3]
console.log 'hi'
Run Code Online (Sandbox Code Playgroud)
the*_*ejh 59
console.log 'hi' for [1..3]
Run Code Online (Sandbox Code Playgroud)
要0正确处理:
console.log 'hi' for [1..n] if n
Run Code Online (Sandbox Code Playgroud)
或者使用原型魔术:
Number::times = (fn) ->
do fn for [1..@valueOf()] if @valueOf()
return
3.times -> console.log 'hi'
Run Code Online (Sandbox Code Playgroud)
请注意,不建议使用第二种方法,因为更改Number原型具有全局效果.
编辑:根据@BrianGenisio的评论(.prototype.- > ::)更改
编辑2:固定处理0,谢谢@Brandon
tok*_*and 32
由于您已经将Underscore.js与CoffeeScript一起使用:
_(3).times -> console.log('hi')
Run Code Online (Sandbox Code Playgroud)
JavaScript数组(至少是现代数组)有一个forEach方法,CoffeeScript [1..3]范围是数组,所以你可以这样做:
[1..3].forEach -> console.log 'hi'
Run Code Online (Sandbox Code Playgroud)
但是有一个警告:如果你的nin [1..n]很大,那么浏览器可能会有点困难,因为你要构建一个大型数组只是为了得到一个方便的符号; 但如果n很小,那么构建阵列的开销应该不会那么重要.