[英]Passing “extra” arguments to a function stored in a variable - Javascript
[英]Passing variable arguments to function
我设置了一个带有可变参数的函数:
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"] ];
想法?
PS我通过在函数中添加这些超简单的行来使其工作。 但是没有其他办法了吗?
if args? and args[0] instanceof Array
args = args[0]
您无需为此手动使用Function.prototype.apply
。 可以在参数中使用Splats列出列表以构建数组,也可以在函数调用中使用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?')
正确的事情将会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.