1

Is it possible to pass multiple ( unknown ) parameters to a function without using an Array?

Take a look at this example code.

var test = function( /* Arguments */ ) { // Number 3
    something( /* All Arguments Here */ );
};


var something = function( first, last, age ) { // Number 2
    alert( first + last + age );
};


test('John', 'Smith', 50); // Number 1 

So the question...

Is it possible to pass the parameters from Number 1 TO Number 2 VIA Number 3 without affecting the way it's used. ie. without an Array.

This could be something to do with OCD but using an array would be nasty looking.

Have I tried anything? Nope, there is nothing i can think of that i can try so.... what can I try? I have searched.....

iConnor
  • 19,997
  • 14
  • 62
  • 97

2 Answers2

4
var test = function() { // Number 3
    something.apply(null, arguments);
};


var something = function( first, last, age ) { // Number 2
    alert( first + last + age );
};


test('John', 'Smith', 50); // Number 1 
user253751
  • 57,427
  • 7
  • 48
  • 90
  • That is a nifty little trick, I always use `call` so it wouldn't have worked, but because `apply` accepts an array it does. Thank you very much.. – iConnor Jul 29 '13 at 09:34
2

I have found the answer to this, thanks to Blade-something

You would use Array.prototype.slice.call(arguments)

var test = function( /* Arguments */ ) {
    something.apply(null, Array.prototype.slice.call(arguments));
};


var something = function( first, last, age ) {
    alert( first + last + age );
};


test('John', 'Smith', 50);

Demo

This example is very useful if you wan't the rest of the arguments and wan't to keep the first one for internal use like so

var test = function( name ) {
    // Do something with name
    something.apply(null, Array.prototype.slice.call(arguments, 1));
};
iConnor
  • 19,997
  • 14
  • 62
  • 97