简体   繁体   中英

How to connect function name with var javascript?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM