我可以使用arguments在函数中获取可变数量的参数,但是如何在不知道其原型的情况下将它们传递给另一个函数?
function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f(arguments); } // not correct, what to do?
run(show, 'foo', 'bar');
Run Code Online (Sandbox Code Playgroud)
注意:我不能保证f传递给函数所需的参数数量run.意思是,即使显示的示例有2个参数,它也可能是0无限,因此以下内容不合适:
function run(f) { f(arguments[1], arguments[2]); }
Run Code Online (Sandbox Code Playgroud)
log*_*yth 28
将以编程方式生成的参数集传递给函数的主要方法是使用函数的"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');
Run Code Online (Sandbox Code Playgroud)
如果我正确理解你的问题,你实际上可以通过申请来做到这一点:
function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f, args) { f.apply(null,args); }
run(show, ['foo', 'bar']);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16432 次 |
| 最近记录: |