将变量参数传递给函数

Passing variable arguments to function

本文关键字:函数 参数传递 变量      更新时间:2023-09-26

我设置了一个带有可变参数的函数:

myfunc: (cmd, args...)->
    # cmd is a string
    # args is an array

可以称为:

myfunc("one") # cmd = "one", args = undefined
myfunc("one","two") # cmd = "one", args = ["two"]
# etc...

现在,如果我想用未知数量的自变量来调用它,该怎么办?假设我想传递一个args数组而不是arg1, arg2, arg3,..,这怎么可能?

尝试myfunc("one",["two","three"])myfunc("one",someArgs)会导致不幸:

# cmd = "one"
# args = [ ["two","three"] ];

想法?


p.S.我通过在函数中添加这些超简单的行来实现这一点。但是没有别的办法吗?

if args? and args[0] instanceof Array
    args = args[0]

您不需要手动使用Function.prototype.apply。Splats可以用于参数列表以构建数组,也可以用于函数调用以扩展数组;来自精细手册:

飞溅

[…]CoffeeScript为函数定义和调用提供了splats ...,使可变数量的参数更容易接受。

awardMedals = (first, second, others...) ->
  #...
contenders = [
  #...
]
awardMedals contenders...

所以你可以这样说:

f('one')
f('one', 'two')
f('one', ['two', 'three']...)
# same as f('one', 'two', 'three')
args = ['where', 'is', 'pancakes', 'house?']
f(args...)
# same as f('where', 'is', 'pancakes', 'house?')

正确的事情就会发生。

演示:http://jsfiddle.net/ambiguous/ztesehsj/

使用Function.apply:

myfunc.apply @, [ "one", "two", "three" ]

CoffeeScript.org 上的演示