繁体   English   中英

将变量参数传递给函数

[英]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?')

正确的事情将会发生。

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

使用Function.apply

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

在CoffeeScript.org上演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM