【问题标题】:After getting unknown number of arguements, pass them to another function获得未知数量的参数后,将它们传递给另一个函数
【发布时间】:2017-03-19 11:31:20
【问题描述】:

作为对以下问题的跟进,我需要将收到的参数发送到另一个函数。

Pass unknown number of arguments into javascript function

例如:

myObj.RunCall("callName", 1,2,3,4,5);
myObj.RunCall("anotherCall", 1);
myObj.RunCall("lastCall");

在哪里

runCall = function(methodName)
{
    // do something clever with methodName here, consider it 'used up'
    console.log(methodName);

    // using 'arguments' here will give me all the 'extra' args
    var x = arguments.length;

    // somehow extract all the extra args into local vars?
    // assume there were 4 (there could be 0-100)

    otherObj.DoIt(arg1, arg2, arg3, arg4);     // here i need to send those "extra" args onwards
}

【问题讨论】:

    标签: javascript methods


    【解决方案1】:

    .apply() method 允许您使用数组中的参数调用函数。所以:

    otherObj.DoIt(1,2,3);
    // is equivalent to
    otherObj.DoIt.apply(otherObj, [1,2,3]);
    

    .apply() 的第一个参数是要在您正在调用的函数中变为 this 的对象。)

    所以您只需要使用来自arguments 的值创建一个数组,您可以使用.slice() 跳过第一个数组:

    var runCall = function(methodName) {
        console.log("In runCall() - methodName is " + methodName);
    
        var extras = [].slice.call(arguments, 1);
        otherObj.DoIt.apply(otherObj, extras);
    }
    
    // simple `otherObj.DoIt() for demo purposes:
    var otherObj = { DoIt: function() { console.log("In DoIt()", arguments); }}
    
    runCall("someMethod", 1,2,3);
    runCall("someMethod", 'a', 'b');
    runCall("someMethod");

    【讨论】:

    • 好的,让我澄清一下,因为我不知道确切会有 4 个,我只想将任何额外的发送到另一个函数
    • 如果它们是“额外”参数,那么“基本”参数是什么?我以为你的意思是 arg1 - arg4 是固定的,然后你想添加来自 arguments 的那些。
    • .apply() 是否返回与原始函数相同的内容?
    • 我想消费 1 个命名的争论(方法名),其余的要传递给 DoIt。
    • 是的,.apply() 返回原始函数的结果。我已经编辑了我现在理解你所问的答案,并包含了一个演示。如果methodName 是您要调用的函数的名称,那么otherObj[methodName].apply(otherObj, [].slice.call(arguments, 1))
    猜你喜欢
    • 2016-02-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多