JavaScript Dynamic Variable Names

心不动则不痛 提交于 2019-11-26 22:54:49

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

Muhammad Irfan

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?

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 ]);
    }); 

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

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

var newCount = 0;
$('#btn').click(function(){

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

jsfiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!