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?
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?
Share Improve this question edited Nov 4, 2011 at 15:27 Pointy 414k62 gold badges595 silver badges629 bronze badges asked Nov 4, 2011 at 15:24 Matteo PagliazziMatteo Pagliazzi 5,27012 gold badges51 silver badges85 bronze badges 7- 4 eval("var editor"+tab_counter); – Birey Commented Nov 4, 2011 at 15:27
- Use an Array – Mat Commented Nov 4, 2011 at 15:28
- and then how could i refer to it dinamically? – Matteo Pagliazzi Commented Nov 4, 2011 at 15:28
- @Birey ick :-) But you're right! – Pointy Commented Nov 4, 2011 at 15:29
- 1 Why do you need to do this? – El Ronnoco Commented Nov 4, 2011 at 15:37
4 Answers
Reset to default 6You 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 pletely correct observation that you can use "eval()" to do what you want.
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);
http://jsfiddle/5ZLYe/
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
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.