Reputation: 5260
I want to create a new variable in javascript but it's name should made of a stale part and a variable one like this:
tab_counter = 1;
var editor + tab_counter = blabla
well i want the new variable name to be in this case editor1, is this possible?
Upvotes: 1
Views: 2151
Reputation: 6258
It seems like you may want to consider using a Dictionary for something like this. This link which references this link describes your options there.
Upvotes: 0
Reputation: 1802
It is possible
var tab_counter=1;
eval("var editor"+tab_counter+"='blah'")
alert(editor1);
eval("var editor"+tab_counter+1+";")
editor2='blahblah';
alert(editor2);
Upvotes: 2
Reputation: 11922
You can do the eval
method used by Birey or you can create a custom property of an object such as...
obj[editor + tab_counter] = blabla;
But it sounds like you're going about doing whatever you're doing in a particularly horrible way. If you just want to store multiple items which you can index into use an array...
var array = [];
array[0] = blabla;
array[1] = blabla2;
alert(array[0]); //shows value of blabla
alert(array[1]); //shows value of blabla2
Upvotes: 1
Reputation: 413737
You cannot create a stand-alone variable name that way (except as a global) (edit or except with eval()
), but you can create an object property:
var tab_counter = 1;
var someObject = {};
someObject['editor' + tab_counter] = "bla bla";
You can create globals as "window" properties like that, but you probably shouldn't because global variables make kittens cry.
(Now, if you're really just indexing by an increasing counter, you might consider just using an array.)
edit also see @Birey's somewhat disturbing but completely correct observation that you can use "eval()" to do what you want.
Upvotes: 6