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?
-
4eval("var editor"+tab_counter);Birey– Birey2011年11月04日 15:27:10 +00:00Commented Nov 4, 2011 at 15:27
-
Use an ArrayMat– Mat2011年11月04日 15:28:10 +00:00Commented Nov 4, 2011 at 15:28
-
and then how could i refer to it dinamically?Matteo Pagliazzi– Matteo Pagliazzi2011年11月04日 15:28:55 +00:00Commented Nov 4, 2011 at 15:28
-
@Birey ick :-) But you're right!Pointy– Pointy2011年11月04日 15:29:31 +00:00Commented Nov 4, 2011 at 15:29
-
1Why do you need to do this?El Ronnoco– El Ronnoco2011年11月04日 15:37:52 +00:00Commented Nov 4, 2011 at 15:37
4 Answers 4
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.
2 Comments
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);
6 Comments
tabs and when you create a new tab store a reference to it in tabs. eg tabs[tab_counter] = newTab.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