Coffeescript中等效的Ruby .times
什么是最简洁的等效Coffeescript以下内容:
# 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' 
 请注意,不build议使用第二种方法,因为更改Number原型具有全局效果。 
  编辑:根据@ BrianGenisio的评论( .prototype. – > :: .prototype. 
编辑2:固定处理0,谢谢@Brandon
既然你已经使用了CoffeeScript的Underscore.js:
 _(3).times -> console.log('hi') 
  JavaScript数组(至less现代的)有一个forEach方法和CoffeeScript [1..3]范围是数组,所以你可以这样做: 
 [1..3].forEach -> console.log 'hi' 
 但是有个警告:如果你的n [1..n]很大,那么在浏览器上可能会有些困难,因为你只是为了得到一个方便的符号而构build一个大的数组。 但是如果n很小,那么构buildarrays的开销不应该太大。 
 console.log 'hi' for[]in length:3 
使用lodash :
 _.times 3, -> console.log 'hi'