0

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.

5
  • plead add a sample usage Commented Aug 4, 2020 at 1:40
  • function SomeFunction(...parameters) would work, but you are doing things backwards. Why apply, when you want the first parameter to be an array? Why not just fn.call(this, parameters), when you expect one argument which is an array? Also, that for loop is quite verbose for let parameters = Array.from(args); Commented Aug 4, 2020 at 1:40
  • 1
    someFunction only has one parameter. When you use apply(), each array element becomes a separate parameter. So the first array element fills in the single parameters variable. Commented Aug 4, 2020 at 1:43
  • 2
    There's no need for the for loop to copy args to parameters. You can just do var parameters = args || []; Commented Aug 4, 2020 at 1:46
  • I am still learning javascript, having been a back end architect for years so I am doing this all from posts and the examples of others.. changing the parse function seems to have worked. Thanks. Commented Aug 4, 2020 at 1:48

1 Answer 1

2

Use ... (rest operator) for parse arguments, will simplify as well as passes array correctly.

function parse(fn, ...parameters) {
  fn = typeof fn == "function" ? fn : window[fn];
  return fn.apply(this, parameters);
}

function SomeFunction(parameters) {
  console.log(parameters);
}

parse(SomeFunction, [1, 2]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.