在While循环语法中传递匿名变量

时间:2013-03-17 16:46:49

标签: coffeescript while-loop

我刚开始使用Coffeescript并运行“在CoffeeScript书中编程”中提供的示例。

在while循环部分,我很感兴趣为什么对times函数的调用必须如下所述声明。

times = (number_of_times, callback) ->
    index = 0
    while index++ < number_of_times
        callback(index)
    return null

times 5, (index) ->
    console.log index

我正在努力阅读代码,当我尝试时:

times (5, (index)) ->
   console.log index

它返回错误。 你能提供一些帮助理解这段代码吗?

1 个答案:

答案 0 :(得分:1)

标准函数定义的结构如下:

name = (arg, ...) ->
    body

所以对你的times定义没什么可说的。那么,让我们看一下您对times的呼吁:

times 5, (index) ->
    console.log index

这部分:

(index) ->
    console.log index

只是另一个函数定义,但这个是匿名的。我们可以使用命名函数重写您的调用,以帮助澄清事情:

f = (index) -> console.log index
times 5, f

我们可以填写可选的括号来拼出来:

f = (index) -> console.log(index)
times(5, f)

一旦所有内容都被细分,您应该会看到5(index)

times 5, (index) ->
   console.log index

彼此无关,所以将它们分组在括号中:

times (5, (index)) ->
   console.log index

没有意义。如果你想在times调用中添加括号以澄清结构(当回调函数更长时这非常有用),你需要知道两件事:

  1. 参数周围的函数名和左括号之间没有空格。如果有空格,那么CoffeeScript会认为您正在使用括号将分组在参数列表中。
  2. 括号需要包围整个参数列表,其中包括回调函数的正文。
  3. 说出来,你会写:

    times(5, (index) ->
       console.log index
    )
    

    或者也许:

    times(5, (index) -> console.log(index))
    

    console.log是一个非原生函数,你甚至可以:

    times(5, console.log)
    

    但是这会给你一个TypeError in some browsers所以不要那么远。

相关问题