JavaScript Dynamic Variable Names [duplicate]
Asked Answered
N

6

12

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.

Nell answered 29/3, 2014 at 6:3 Comment(1)
Don't use "dynamic variable names". Use the appropriate Map (plain Object) or Sequence (Array).Forward
G
34

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

Gasometry answered 29/3, 2014 at 6:8 Comment(0)
L
2

you can use window

var window['hello' + newCount ] = '<p>Hello World</p>';

likewise..

newCount = document.getElementById('hello').innerHTML;
    $('.hello').click(function(){
        //set count fast enumeration
        newCount++;
        var window['hello' + newCount ] = '<p>Hello World</p>';
        alert(window['hello' + newCount ]);
    }); 
Latchkey answered 29/3, 2014 at 6:7 Comment(2)
why -1 to my answer? this also will wrk.. its not wrongLatchkey
It is wrong. When you get a downvote, maybe you should take the time to test your code.Steepen
W
2

In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:

eval Function
window object
eval:

var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);
window object:

var pageNumber = 1;
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);

for more inforamtion How do i declare and use dynamic variables in javascript?

Wixted answered 29/3, 2014 at 6:8 Comment(0)
L
1

I would just use a simple array to store the variables. Then the object with index n would be variable n etc..

Linker answered 29/3, 2014 at 6:8 Comment(0)
S
0

Most simple way

var types = {};

for(var i=1; i<=3; i++){
types["ashish"+i] = 'The value of dynamic variable, val';
}

console.log(types);

you can test it on

jsfiddle

Shaer answered 14/7, 2017 at 7:33 Comment(1)
great stuff, thanks :)Lifton
W
-2
var newCount = 0;
$('#btn').click(function(){

    newCount++;
    $('#hello').html('hello' + newCount);
}); 

jsfiddle

Wouldst answered 29/3, 2014 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.