Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments array to another function in JavaScript? [duplicate]

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.

like image 459
at. Avatar asked Mar 22 '23 17:03

at.


1 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);
}
like image 188
AlexCheuk Avatar answered Apr 05 '23 22:04

AlexCheuk