John Cowan
John Cowan

Reputation: 1674

How to create dynamic call to javascript function

JavaScript question. I'm completely drawing a blank this morning.

I have four functions:

function create_account1(){  // some stuff  }
function create_account2(){  // some stuff  }
function create_account3(){  // some stuff  }
function create_account4(){  // some stuff  }

I now have need to loop through some numbers and if a criteria is met, call the appropriate function. Since I don't know which number I'm on in the loop, how can I do this?

simple example:

for( var i=1; i<=4; i++ ){
  create+i+(); 
}

That does not work and I've tried variations, but can get it working.

Thanks for any suggestions. johnC

Upvotes: 0

Views: 60

Answers (4)

ComFreek
ComFreek

Reputation: 29424

Do these function live in the global context?

If so, you could use this:

for( var i=1; i<=4; i++ ){
  window["create_account" + i](); 
}

FYI: If you want to test this in a jsFiddle, be sure to not use the onLoad or onDomready wrap settings of jsFiddle. If you try to use them, your functions will become nested ones which obviously don't belong to the window object anymore.

Upvotes: 2

Kuldeep Raj
Kuldeep Raj

Reputation: 795

Please do by this:

 for( var i=1; i<=4; i++ ){
  var fnName = 'create_account' + i ;
  //create+i+();
  window[fnName]();
}
function create_account1(){

  alert('Hello');

}

Upvotes: 1

Tomzan
Tomzan

Reputation: 2818

You cannot call function like this. I think you're facing design problem, the proper way to do it is something like this:

function create_account(accountID) {
    switch(accountID)
    {
        case 1: 
        {
            //account 1 logic.
            break;
        }
        case 2:
        {
            //account 2 logic.
            break;
        }
        etc...
    }
}

And you call it like this

for( var i=1; i<=4; i++ ){
  create_account(i); 
}

Upvotes: 0

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

Try this

 function mainfunc (){
    window[Array.prototype.shift.call(arguments)].apply(null, arguments);
 }

The first argument you pass should be a function name to call, all the rest of the arguments would be passed onto the called function. In your case,

mainfunc('create_account1');

or

mainfun('create_account2', 'Name');

if you need to pass a name for create_account2.

Upvotes: 1

Related Questions