I'm looking for a way to create variables dynamically in javascript
eg
I have a loop
for (i=0;i<15;i++){
}
now I need to create variables dynamically eg var "a"+i for eavh value in the loop. Is this possible and how?
If we presume that you will need several variables related to each iteration ([foo1,bar1], [foo2, bar2]...) then there are two approaches
Use arrays
var foo = [], bar = [];
foo[1] = "foo";
bar[1] = "bar";
Use an object
var myVars = {};
myVars["foo" + 1] = "foo";
myVars["bar" + 1] = "bar";
That last one could also be written as
myVars.bar1 = "bar";
Do not use eval as some has suggested.
eval is only 'evil' if used wrong, so don't listen to everything The Crock says..You can use the evil eval function for this purpose:
for (var i=0; i < 15; i++){
eval( 'var a' + i + ' = "something"' );
}
var array = []; for (i=0;i<15;i++){array[i] = ...}?