javascriptfunctionfor-loopconditional-execution

Javascript function as a variable in loop


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(){};
}

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.