Arshan Khanifar
Arshan Khanifar

Reputation: 301

calling a function with multiple parameters stored in an array in javascript

I searched around and didn't really find a question regarding this.

So I have a function which can take multiple parameters ,(the number of parameters doesn't matter) something like this:

function print(){
    for(var i = 0; i<arguments.length; i++ ){
        console.log(arguments[i]);
    }
}

and I have all the parameters in an array, like:

var params = [param1,param2,...];

I need to call the function with those parameters stored in the params array. Well, I could do this if I knew the number of params:

print(params[0],params[1],...);

but I don't know the number of params and need a way to call the function with all of them.

Is there anyway I can do this? I tried using print.call(params), but the call method doesn't work that way.

thanks

Upvotes: 2

Views: 1060

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

In ES5 and earlier, you're looking for Function#apply, which all true JavaScript functions have:

console.log.apply(console, params);

...where params is your array.

Function#apply calls the function you call it on with a given this value (the first argument) and as many arguments as there are in the array you give it.

Note that it's not guaranteed that all host-provided functions (like console.log) will be true JavaScript functions. In modern browsers, however, console.log does have apply. YMMV on, say, IE9 and earlier.

In ES2015 (ES6) and later, you'd use the spread operator:

// ES2015 and later only
console.log(...params);

...again where params is your array.

Upvotes: 2

Related Questions