作为以下问题的后续内容,我需要将收到的论据发送给另一个函数。
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
}
答案 0 :(得分: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");