0

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(){};
}
4
  • 3
    Can't you just use function menu(num){ .. }? Commented Feb 21, 2014 at 12:27
  • There is no way to make a single menu function that accepts a "menuNumber" argument? Commented Feb 21, 2014 at 12:27
  • What happened to menu2? :) Commented Feb 21, 2014 at 12:30
  • stackoverflow.com/questions/3733580/… Have a look into this. Commented Feb 21, 2014 at 12:31

3 Answers 3

1

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.

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

Comments

0

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.

Comments

0

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.

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.