传递变量参数功能
问题描述:
我已经设置可变参数的函数:传递变量参数功能
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...
现在,如果我要什么有数目不详的调用它的论点? 假设我想传递一组参数而不是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可以用于参数列表以构建数组或在函数调用中展开数组;从the fine manual:
提示图标...
[...]的CoffeeScript提供泼溅
...
,既为函数的定义,以及调用,使得参数一点点更可口变量的数字。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?')
和正确的事情会发生。
真棒!非常感谢! :-) – 2014-11-08 13:07:04