简体   繁体   English

获得未知数量的论据后,将其传递给另一个函数

[英]After getting unknown number of arguements, pass them to another function

As a follow up to the below question, I have a need to send the arguments I received to another function. 作为以下问题的后续,我需要将收到的参数发送给另一个函数。

Pass unknown number of arguments into javascript function 将未知数量的参数传递给javascript函数

For example: 例如:

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

where 哪里

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
}

The .apply() method lets you call a function with arguments that are in an array. .apply()方法使您可以使用数组中的参数调用函数。 So: 所以:

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

(The first argument to .apply() is the object that is to become this within the function you are calling.) .apply()的第一个参数是要在要调用的函数中成为this对象的对象。)

So you just need to create an array with the values from arguments , which you can get using .slice() to skip the first one: 因此,您只需要使用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"); 

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

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