如何将参数数组传递给 JavaScript 中的另一个函数

How to pass arguments array to another function in JavaScript?

本文关键字:JavaScript 另一个 函数 参数 数组      更新时间:2023-09-26

我在 JavaScript 中有一个函数:

function test() {
  console.log(arguments.length);
}

如果我用 test(1,3,5) 调用它,它会打印出3,因为有 3 个参数。如何从另一个函数中调用测试并传递另一个函数的参数?

function other() {
  test(arguments); // always prints 1
  test(); // always prints 0
}

我想调用other并让它使用其arguments数组调用test

看看apply()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

function other(){
    test.apply(null, arguments);
}

你为什么不尝试像这样传递参数呢?

function other() {
  var testing=new Array('hello','world');
  test(testing); 
}
function test(example) {
  console.log(example[0] + " " + example[1]);
}

输出:hello world

这是一个有效的JSFiddle: