Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Dynamic Variable Names

Ok so I want to create variables as a user clicks threw the code every click adds a new variable. I am currently using jquery and javascript I can't do it server side this must be done in the browser.

newCount = document.getElementById('hello').innerHTML;
    $('.hello').click(function(){
        //set count fast enumeration
        newCount++;
        var hello + newCount = '<p>Hello World</p>';
    }); 

so I want the variables to be hello1, hello2, hello3, hello4, etc.

like image 533
Cody Weaver Avatar asked Mar 29 '14 06:03

Cody Weaver


People also ask

How do I create a dynamic variable name?

Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.


1 Answers

You can only do that with bracket notation, which means you have to attach the variables to something.
The global scope would be window, so that would be window['hello' + newCount], but polluting the global namespace with a bunch of random properties doesn't sound like a good idea, so using an object seems better

var vars = {};
var newCount = parseInt($('#hello').html(), 10);

$('.hello').click(function(){
    newCount++;
    vars['hello' + newCount] = '<p>Hello World</p>';
}); 

alert( vars['hello1'] );

FIDDLE

like image 142
adeneo Avatar answered Sep 21 '22 21:09

adeneo