1

I have a series of numbered javascript functions and I would like to loop through the functions based on a variable called total. If total is 3, I would like to run load1(data), load2(data), load(3) data; if it is 2 just the first two functions so on.

This seems simple enough, but I can't seem to get it working right. In the simplest form the code below works.

i = 1;
if (i <= total){load1(data);}i++;
if (i <= total){load2(data);}i++;
if (i <= total){load3(data);}i++;
if (i <= total){load4(data);}i++;
if (i <= total){load5(data);}

But I can't seem to be able to put that in a loop. I have tried the following:

Trying to put the functions in an array and calling them in a for loop based on this thread. //throws a function undefined error.

Call it inside a loop like this:

var f = new Function("return load"+i+"(data)")(); //throws a data not defined error

Any suggestions?

Community
  • 1
  • 1
Helius 06
  • 87
  • 1
  • 12

1 Answers1

0

If loadX is global function, you could do like below:

for (var i = 1; i <= total; i++) {
  window['load'+i](data);
}
xdazz
  • 158,678
  • 38
  • 247
  • 274