最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: give a variable a name made of 2 variables - Stack Overflow

programmeradmin0浏览0评论

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
 |  Show 2 more ments

4 Answers 4

Reset to default 6

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 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.

发布评论

评论列表(0)

  1. 暂无评论