Question

Can you please help me with one loop with functions:

I have 7 functions:

function menu1(){};
function menu3(){};
function menu4(){};
function menu5(){};
function menu6(){};
function menu7(){};

And what i need to do is load as a function menux(){} I mean from the loop if x == 3 load function menu3().

for(x=1;x=8;=x++)
{
    function menux(){};
}
Was it helpful?

Solution

You can wrap your function into an object:

function menu1(){};
function menu3(){};
function menu4(){};
function menu5(){};
function menu6(){};
function menu7(){};

var wrap={
    menu1:menu1;
    menu3:menu3;
    menu4:menu4;
    menu5:menu5;
    menu6:menu6;
    menu7:menu7;
}

And then, you can cosume that into the for:

for(x=1;x=8;=x++)
{
  if(!wrap["menu"+i]) wrap["menu"+i]();
}

There are a lot of ways of doing that, you can also do:

function menu(int num){
 switch(num)
  {
   case 1:
    menu1();
    break;
   case 2:
    menu2();
    break;

   //....
  }
}

I hope that it helps.

OTHER TIPS

You should probably explain your situation and what you want to achieve in the bigger picture. This seems like a suboptimal approach already. But well, here you go:

for(var x=1; x<8; x++)
{
    window['menu' + x]();
}

Assumuing your function declarations are in global namespace, this loop will call all those functions from menu1 to menu7.

You should ask yourself - if there's a different way. And of course it is!

  1. I suggest you to make a function which accept an argument and does something based on it like: function menu(x) {...}

  2. If the first option is not available for you, I would suggest you do implement an object with these methods like this: var methods = { menu1: function() {}, menu2: function() {}, menu3: function() {}, ... }

  3. use eval. Please don't do that in this case. Eval is powerful but in such cases it's an overkill.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top