Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将可变数量的参数从一个函数传递到另一个函数_Javascript - Fatal编程技术网

Javascript 将可变数量的参数从一个函数传递到另一个函数

Javascript 将可变数量的参数从一个函数传递到另一个函数,javascript,Javascript,可能重复: 我可以使用arguments在一个函数中获取数量可变的参数,但是如何在不知道其原型的情况下将它们传递给另一个函数呢 function show(foo, bar) { window.alert(foo+' '+bar); } function run(f) { f(arguments); } // not correct, what to do? run(show, 'foo', 'bar'); 注意:我无法保证传递给run的函数f所需的参数数量。这意味着,即使所示示例有2个参数

可能重复:

我可以使用
arguments
在一个函数中获取数量可变的参数,但是如何在不知道其原型的情况下将它们传递给另一个函数呢

function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f(arguments); } // not correct, what to do?
run(show, 'foo', 'bar');
注意:我无法保证传递给
run
的函数
f
所需的参数数量。这意味着,即使所示示例有2个参数,它也可能是0-无限的,因此以下不合适:

function run(f) { f(arguments[1], arguments[2]); }

您需要使用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');  

如果我正确理解了您的问题,您实际上可以使用apply来执行此操作:

function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f, args) { f.apply(null,args); } 
run(show, ['foo', 'bar']);

将编程生成的参数集传递给函数的主要方法是使用函数的“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');

在您的示例中,传递变量参数以显示此功能

function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f.apply(null, Array().slice.call(arguments, 1)); }
run(show, 'foo', 'bar');  

我不同意,正如您所看到的,
show
已经定义了参数,它没有使用
参数。我已经尝试过用这种方式应用了,但没有运气。好吧,正如你现在注意到的,
apply
是唯一可以这样做的方法,因此它是重复的。是的,除了
参数使用的方式完全不同,最终是问题的关键。问题是,我已经有了一个使用
参数的框架设置,不想将所有调用都切换到使用数组。在同样的情况下,我可以尝试将
参数
从一个对象转换为一个数组并传递它。看看@Logan的解决方案,它似乎可以满足您的需要。对于后代,如果函数是一个对象方法,并且需要保持它的上下文,则使用
f传递
this
对象,而不是
null
(this,args);