Roland
Roland

Reputation: 9701

Pass optional multiple arguments to a function

This might be a duplicate but I had little success in finding the right answer. I'm trying to achieve something like this :

var joinArrays = function(myCollectionOfArguments) {
    return array.concat(array1, array2, ..... , arrayN);
};

In which case myCollectionOfArguments will be array1, array2, ..... , arrayN. How could I achieve something like that ? I do know that if I had a callback function I cold pass as many arguments as I would like using .apply(), but in this certain case I'm a bit confused on the approach.

EDIT : So, to be more descriptive : Instead of passing just one argument, I would to be able to pass as many as I want without having to specify it when I define the function's arguments, in my case myCollectionOfArguments, would be just one argument when defining the function, but when I want to use the function I want to be able to pass more than one argument ;

Upvotes: 0

Views: 116

Answers (4)

Bergi
Bergi

Reputation: 664406

You can use the arguments object for an arbitrary amount of arguments, and you can even pass that directly into .apply:

var joinArrays = function() {
    return [].concat.apply([], arguments);
};

Btw, using bind would be more elegant here:

var joinArrays = Array.prototype.concat.bind([]);

Upvotes: 4

Yoshi
Yoshi

Reputation: 54649

If I get your intention right, try:

var joinArrays = function(a) {
  return a.concat.apply(a, Array.prototype.slice.call(arguments, 1));
};

var foo = joinArrays([1, 2], [3, 4], [5, 6]);

console.log(foo); // => [1, 2, 3, 4, 5, 6] 

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Not sure I understand, but you can pass arbitrary number of arrays:

joinArrays([1,2,3], [4,5,6], [7,8], [9,10,11,12])

and later read all of them using special arguments variable inside joinArrays().

Upvotes: 0

zachzurn
zachzurn

Reputation: 2201

function testFunction()
{
    var arg1 = arguments[0];
    var arg2 = arguments[1];
    var arg3 = arguments[2];
}

Upvotes: 0

Related Questions