【问题标题】:Passing variable arguments to function将变量参数传递给函数
【发布时间】:2015-01-05 03:58:27
【问题描述】:

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

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]

【问题讨论】:

    标签: javascript variables coffeescript argument-passing


    【解决方案1】:

    使用Function.apply

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

    Demo on CoffeeScript.org

    【讨论】:

    • 太棒了!非常感谢! :-)
    【解决方案2】:

    您无需为此手动使用Function.prototype.apply。 Splats 可用于 list 的参数以构建数组或用于函数调用以扩展数组;来自the fine manual

    喷溅...

    [...] 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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 2022-06-10
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多