等价Ruby .times在Coffeescript [英] Equivalent Ruby .times in Coffeescript

查看:104
本文介绍了等价Ruby .times在Coffeescript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最简洁的等效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]

c $ c> 0 正确:

To also handle 0 correctly:

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的注释改变(。原型。 - > ::

Changed according to @BrianGenisio's comment (.prototype. -> ::)

2:固定处理为0,感谢@Brandon

Edit 2: fixed handling of 0, thanks @Brandon

这篇关于等价Ruby .times在Coffeescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆