3

I defined a function that can take any number of arguments but none is required:

function MyFunction() { //can take 0, 1, 1000, 10000, n arguments
//function code
}

Now i would like to write another function that call MyFunction with a variable number of arguments each time:

function Caller(n) {
var simple_var = "abc";
MyFunction() //how can i pass simple_var to MyFunction n times?
} 

Thanks in advance :)

1
  • 1
    You should not name your functions uppercase as long as they are no constructors. Commented Apr 27, 2012 at 10:56

2 Answers 2

8

Function.apply can be used to pass an array of arguments to a function as if each element in the array had been passed as an individual argument:

function Caller(n) {
   var simple_var = "abc";

   // create an array with "n" copies of the var
   var args = [];
   for (var i = 0; i < n; ++i) {
      args.push(simple_var);
   }

   // use Function.apply to send that array to "MyFunction"
   MyFunction.apply(this, args);
}

Worth to say, argument length is limited to 65536 on webkit.

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

6 Comments

1. Use args[args.length] instead of args.push() 2. Your solution submits an array as parameter, not n different parameters.
@Amberlamps - apply is used for this very situation. It will submit n arguments
@Amberlamps you're wrong - .call is used to send it as an array, .apply to send it as a list of parameters.
@Amberlamps also there's negligible performance difference between array.push() and args[args.length] - see jsperf.com/array-push-and-append-by-index
@Alnitak: Lol, I picked up a different statistic a while ago, but I cannot find it anymore. That proves again that you cannot really trust the internet :)
|
-3

You can use eval (I know, eval is evil).

In for loop construct string:

var myCall = "Myfunction(abc, abc, abc)";

and then pass it to eval

function Caller(n) {
var simple_var = "abc";
  eval(myCall);
} 

1 Comment

never, ever, ever, use eval.

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.