Is it possible to call a JavaScript function using an array of values ​​as arguments?

I am looking for another way to do the following:

function call_any_function(func, parameters){
    // func => any given function
    if(parameters.length==0){ func(); }    
    if(parameters.length==1){ func(parameters[0]); }    
    if(parameters.length==2){ func(parameters[0], parameters[1]); }    
    if(parameters.length==3){ func(parameters[0], parameters[1], parameters[2]); }    
    if(parameters.length==4){ func(parameters[0], parameters[1], parameters[2], parameters[3]); }
    // ... and so on
};

      

Seems basic, but I couldn't find an answer.

Any ideas?

+2


a source to share


1 answer


Oh yeah:

func.apply({}, parameters)

      



the first parameter is what you want to this

be inside the function.

+6


a source







All Articles