Question

I have 2 JavaScript functions that dynamically-named..

function a1(){
   //some codes
}

function a2(){
   //some codes
}

function a3(){
   //some codes
}

these functions above generated by PHP for sure..

<?php 
  for($i = 1; $i <= $load_period->count; $i++){ 
?>
  <script type="text/javascript">
  function a<?php echo $i;?>(){
     //javascript functions
  }
  </script>
<?php 
  } 
?>

now I have to call both of these functions with for..

for(var i= 1; i <= 3; i++){
   // here the solution code .. 
   // doesn't work >> a+i+();
}
  • NB 1 : it's doesn't work with "a+i+();" .
  • NB 2 : I don't want to use "EVAL" syntax

thanks for any solution..

Was it helpful?

Solution

If the functions are globally accessible you may write

window['a'+i]()

Otherwise, you may be able to rewrite your code to add all the functions to one variable:

var f = {
    a1: function() { },
    a2: function() { },
    a3: function() { }
};

... and call f['a'+i]().

If you're rewriting, since all functions are named by an index, you might as well write:

var myFunctions = [
  function() { },
  function() { },
  function() { }
];

... and call myFunctions[i](). (Of course, as Felix Kling points out in comments, i here would have to be adjusted to be 0-based).

OTHER TIPS

If they're global functions, you can do:

window['a' + i]()

Otherwise, you have to use eval (and frankly, this is a perfect use case for eval, because nothing else works):

eval('a' + i)()

JavaScript doesn't provide you with access to the variables in the current scope through an object (Python does this with locals() and globals()), so eval is your only choice if you cannot rewrite that code.

if the methods are in global scope then

for(var i= 1; i <= 3; i++){
    window['a' + i]()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top