0

How to connect function name with var javascript ?

i want to connect myFunction with var zz.

i try to like this but not work, how can i do that ?

<script>
for(var zz = 0; zz < 3; zz++)
{
    function myFunction'+var zz+'() {
         -------------SOME CODEING---------------
        } 
}
</script>
8
  • 1
    Define function outside of the loop, pass a param into its call (myFunction(zz);). Commented Dec 1, 2014 at 17:07
  • you may use eval() but no good practive at all Commented Dec 1, 2014 at 17:08
  • 3
    dynamic function names? That is NEVER a good idea... Commented Dec 1, 2014 at 17:09
  • Avoid to use it. But.. stackoverflow.com/questions/5905492/… Commented Dec 1, 2014 at 17:11
  • 1
    I smell a bad practice. What problem are you trying to solve by doing this? Commented Dec 1, 2014 at 17:14

1 Answer 1

2

Perhaps a good way of doing this is to store your functions in an object and then reference those in your loop:

var obj = {
    fn0: function () {
        console.log(0);
    },
    fn1: function () {
        console.log(1);
    },
    fn2: function () {
        console.log(2);
    }
}

for (var zz = 0; zz < 3; zz++) {
  var fnName = 'fn' + zz;
  obj[fnName]();
}

Or perhaps even better:

for (var zz = 0, l = Object.keys(obj).length; zz < l; zz++) {
  var fnName = 'fn' + zz;
  obj[fnName]();
}

DEMO

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

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.