How to pass an array of arguments to another function in JavaScript?

I have a function in JavaScript:

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

if I call it test(1,3,5), it outputs 3, because there are 3 arguments. How can I call a test from another function and pass other arguments to the function?

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

I want to call otherand call it testwith an array arguments.

+4
source share
2 answers

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);
}
+7
source

Why don't you try passing such arguments?

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

Exit: hello world

This is where JSFiddle works :

0

All Articles