I am using the following code to pass an array to variable javascript functions
function parse(fn, args)
{
var parameters = [];
if (args)
{
for (var i = 0; i < args.length; i++)
{
parameters.push(args[i]);
}
}
fn = (typeof fn == "function") ? fn : window[fn];
return fn.apply(this, parameters);
}
function SomeFunction(parameters)
{
console.log(parameters);
}
This works, to an extent, as the right function is called and the parameters are passed to it. However, I only receive the first element of the array in the function, which is obviously the issue I am having as I need all the elements of the array not simply the first.
function SomeFunction(...parameters)would work, but you are doing things backwards. Whyapply, when you want the first parameter to be an array? Why not justfn.call(this, parameters), when you expect one argument which is an array? Also, that for loop is quite verbose forlet parameters = Array.from(args);someFunctiononly has one parameter. When you useapply(), each array element becomes a separate parameter. So the first array element fills in the singleparametersvariable.forloop to copyargstoparameters. You can just dovar parameters = args || [];