4

I have a function in JavaScript:

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

if I call it with test(1,3,5), it prints out 3 because there are 3 arguments. How do I call test from within another function and pass the other function's arguments?

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

I want to call other and have it call test with its arguments array.

at.
  • 50,922
  • 104
  • 292
  • 461

2 Answers2

7

Take a look at apply():

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

function other(){
    test.apply(null, arguments);
}
AlexCheuk
  • 5,595
  • 6
  • 30
  • 35
  • 4
    I think you meant `test.apply(this, arguments);` – Michael Lorton Nov 09 '13 at 02:11
  • "if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed." But yeah, it will work either way. `this` only needs to be used when you actually want to pass it. – FabianCook Nov 09 '13 at 02:14
0

Why don't you try passing the arguments like this?

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

Output: hello world

Here's a working JSFiddle:

Waclock
  • 1,686
  • 19
  • 37
  • I think the OP just wants to know how to pass dynamic parameters to other functions without hardcoding – AlexCheuk Nov 09 '13 at 02:30
  • And if the test function to be called was made by the other package or encapsulated, he just wants to pass the same params into that function. – kakadais Sep 08 '15 at 17:38