View Full Version : Defining a variable with another variable

12-30-2007, 02:47 AM
Hi all!

I've just started with programming in javascript, and I've run into a problem that I haven't been able to find an answer to in any books or on the web. I was hoping someone could help.

I've been trying to call a variable so that I can set it equal to something by using another variable's value as part of the name. Something like this:

var test1 = "blah";
var i = 1;

test+i = "It Worked";

Now if this worked the way that I wanted, then test1 would now contain the phrase "It Worked." Does anyone know what I can do to make this work? I've tried reading up on this and I cannot find a way to do this. I hope someone can help.


12-30-2007, 03:50 AM
Arrays (http://en.wikipedia.org/wiki/Array) are what you are looking for:

var test = []; // or... var test = new Array();
var i = 1;

test[i] = "It Worked";


12-30-2007, 03:53 AM
actually, i cannot use an array to do what i need to do, i was curious if what i put up before was possible. I know it must be but i'm just not sure how to do it.

thanks for trying to help though :)

12-30-2007, 04:25 AM
You want to do reflection?

var test1 = "blah";
var i = 1;

window["test"+i] = "It Worked";


12-30-2007, 04:36 AM
awesome that worked! i didn't know it was called a reflection. thanks man.

12-30-2007, 04:57 AM
Glad that was what you had wanted.

If you want to read up more on reflection:

In particular, here's a JS example: