iConnor
iConnor

Reputation: 20189

Passing multiple parameters to a function via a function

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.....

Upvotes: 1

Views: 81

Answers (2)

iConnor
iConnor

Reputation: 20189

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

Upvotes: 2

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 

Upvotes: 4

Related Questions