0

Since I've started programming in JavaScript fairly recently (around 3-4 weeks ago), I've been getting quite into it. I still keep finding new methods and to do certain tasks, statements, etc. Currently, I'm doing a bit of experiment on it by doing a simple text adventure game.

HTML code:

 <!DOCTYPE html>
 <html>
 <head>
 <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
 <script src="game.js"></script>
 </head>
 <body>
      <input type="text" maxlength="20"></input>
      <button>Enter</button>
 </body>
 </html>

But I was thinking that instead of adding a switch statement and add each case with its own calling of the function, I wanted to try something out but am unsure how to achieve it.

Instead of this:

 //game.js
 var storySection = 0;
 var user;

 $(document).ready(function(){
      $('button').click(function(){
           user = $('input').val();

           switch(storySection){
                case 0:
                   _0();
                   break;
                case 1:
                   _1();
                   break;
                case 2:
                   _2();
                   break;
                //And so on...
           }
      });
 });

I wanted to use something like this:

 //game.js
 var storySection = 0;
 var user;

 $(document).ready(function(){
      $('button').click(function(){
           user = $('input').val();

           '_' + storySection + ();
      });
 });

I guess something along those lines, but I was wondering is it possible? Do I have to do some kind of work around it or do I have to forcefully use switch statements...?

  • 1
    That's the wrong duplicate. You want [How to execute a JavaScript function when I have its name as a string](http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) – Liam Jun 17 '16 at 08:34
  • you can refer following code – sandesh jadhav Jun 17 '16 at 08:44
  • 1
    @Liam — No. The duplicate is correct. Variable variables are just the more general expression of it. "How to execute a JavaScript function when I have its name as a string" basically means the same as "How do I execute a function that is the value of a variable variable?" – Quentin Jun 17 '16 at 08:48
  • 1
    @sandeshjadhav — Don't answer in the comments. If you have an answer that is better than the ones on the duplicate question, then answer there. – Quentin Jun 17 '16 at 08:48

0 Answers0