Coffeescript中的等效Ruby .times

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

  • 我之所以选择这个答案是因为它只使用了Coffeescript. (3认同)
  • 只是为了玩一下,我建议使用CoffeeScripts` ::`operator:`Number :: times =(fn) - >`这是CoffeeScript方式:) (3认同)
  • 请注意,这个原型魔法是由[Sugar.js](http://sugarjs.com/)库添加的.真的,使用原型魔法并没有什么不妥,只要你的应用程序中只有一部分是这样做的 - 所以你没有不同的东西期待不同的原型魔法. (2认同)
  • 范围实际上应该是[0 ... @ valueOf()].正如当前所写,当@valueOf()等于1时,fn被调用为零次,而当@valueOf()等于0时,fn被调用一次. (2认同)

tok*_*and 32

由于您已经将Underscore.js与CoffeeScript一起使用:

_(3).times -> console.log('hi')
Run Code Online (Sandbox Code Playgroud)

  • tokland - 你的答案实际上是我将在我的代码中使用的答案因为我使用了underscore.js,但我选择了@ thejh的答案,因为我的问题是关于Coffeescript.很抱歉,我无法回答你的问题.=( (4认同)
  • 第1行的@NicolasGoy SyntaxError:`large`是一个形容词.一个人不能建立一个"大". (2认同)

mu *_*ort 8

JavaScript数组(至少是现代数组)有一个forEach方法,CoffeeScript [1..3]范围是数组,所以你可以这样做:

[1..3].forEach -> console.log 'hi'
Run Code Online (Sandbox Code Playgroud)

但是有一个警告:如果你的nin [1..n]很大,那么浏览器可能会有点困难,因为你要构建一个大型数组只是为了得到一个方便的符号; 但如果n很小,那么构建阵列的开销应该不会那么重要.