0

I've searched a bit and come up with .apply() and .call(), but they don't seem to behave as I need them to.

Say I have

function example(someparam, anotherparam, finalparam){
}

Am I able to dynamically pass it an array to match those parameters? Such that if I was trying to pass value1 to 'someparam,' value2 to 'anotherparam,' and value3 to 'finalparam,' I could do so with an array like [value1, value2, value3]?

Say if those values were:

valueArray = [value1, value2, value3];

I thought it might be possible to do

example.apply(valueArray);

Is this possible? I understand that it's possible to deal with parameters dynamically by passing objects, but I need this to not require that the target function expects an object.

ralusek
  • 25
  • 3
  • Possible duplicate of [Passing an array as a function parameter in JavaScript](http://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript) – TylerH Jul 28 '16 at 03:22

2 Answers2

1

Your code is incomplete...you can use

example.apply(this, valueArray);
StaleMartyr
  • 778
  • 5
  • 18
0

Javascript functions can be passed any number of parameters, the remaining will just be undefined.

In the example function you can use arguments.length. If it's 1, assume you were passed an array with the three values. Otherwise carry on as normal. You can also just check the type of the first parameter or check the type of the last two. Something like:

function example(someparam, anotherparam, finalparam){
    if(typeof someparam === "Array") {
        finalparam = someparam[2];
        anotherparam = someparam[1];
        someparam = someparam[0];
    }

    //continue as normal
}

If you can't modify the function, then you can just use example.apply(undefined, valueArray).

Jahed
  • 484
  • 2
  • 8