javascript 将可变数量的参数从一个函数传递到另一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7301062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing variable number of arguments from one function to another
提问by steveo225
Possible Duplicate:
Is it possible to send a variable number of arguments to a JavaScript function?
I can use arguments
to get a variable number of arguments within a function, but how can I pass them to another function without knowing its prototype?
我可以使用arguments
在函数中获取可变数量的参数,但是如何在不知道其原型的情况下将它们传递给另一个函数?
function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f(arguments); } // not correct, what to do?
run(show, 'foo', 'bar');
Note: I cannot guarantee the number of arguments needed for the function f
that is passed to run
. Meaning, even though the example shown has 2 arguments, it could be 0-infinite, so the following isn'tappropriate:
注意:我不能保证f
传递给run
. 意,尽管示出的实施例具有2个参数,它可以是0无穷大,所以下面是不恰当:
function run(f) { f(arguments[1], arguments[2]); }
回答by loganfsmyth
The main way to pass a programmatically generated set of arguments to a function is by using the function's 'apply' method.
将以编程方式生成的参数集传递给函数的主要方法是使用函数的“apply”方法。
function show(foo, bar) {
window.alert(foo+' '+bar);
}
function run(f) {
// use splice to get all the arguments after 'f'
var args = Array.prototype.splice.call(arguments, 1);
f.apply(null, args);
}
run(show, 'foo', 'bar');
回答by spike
You can in fact do this with apply, if I understand your question correctly:
如果我正确理解您的问题,您实际上可以通过申请来做到这一点:
function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f, args) { f.apply(null,args); }
run(show, ['foo', 'bar']);
回答by Baz1nga
you need to use the apply function.. here is how u do it:
你需要使用apply函数..这是你如何做到的:
function variableFunction1()
{
alert("variableFunction1 arguments length: " + arguments.length);
// calls second varargs function keeping current 'this'.
variableFunction2.apply(this, arguments);
}
function variableFunction2()
{
alert("variableFunction2 arguments length: " + arguments.length);
}
variableFunction1('a','b','c');
回答by James Kyburz
In your example to pass variable arguments to show this works
在您的示例中传递变量参数以显示此工作
function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f.apply(null, Array().slice.call(arguments, 1)); }
run(show, 'foo', 'bar');