Creating Arrays via Button click

is it possible to make a button CREATE an array, for instance:

btn.addEventListener('click', function(){

    var arrayName = prompt('new array');

    //  Create an array with the variable name set to the string stored in 
    //  arrayName
});

i've looked everywhere for something like this with no luck.

2 answers

  • answered 2017-08-16 19:34 Wizard

    You can use an object to hold all your dynamically created arrays:

    var userArrays = {};
    
    btn.addEventListener('click', function() {
        var arrayName = prompt('new array');
        userArrays[arrayName] = [];
    });
    

  • answered 2017-08-16 19:34 S.P.H.I.N.X

    You may add a button in HTML with an id. Then, you have to get it in your javascript code with the method: document.getElementById ("anId");. Next, your listener is OK for me. You just need to use the string like an array or to use the split method if you want to cut the string in order to create some case like every spaces.

    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Simple Teste</title>
      <style>
    
      </style>
    </head>
    
    <body>
      <button id="create">Create</button>
      <script>
    
      var btn = document.getElementById ("create");
    
    
        btn.addEventListener('click', function () {
    
          var arrayName = prompt('new array');
    
          //  Create an array with the variable name set to the string stored in 
          //  arrayName
    
          console.log (arrayName[3]);
    
        });
      </script>
    
    </body>
    
    </html>
    

    Tell me if you have some comments or some questions.