How do I create dynamic variable names inside a loop?
I'm working on an ajax google maps script and I need to create dynamic variable names in a for loop.
for (var i = 0; i < coords.length; ++i) {
var marker+i = "some stuff";
}
What I want to get is: marker0
, marker1
, marker2
and so on.
and I guess there is something wrong with marker+i
Firebug gives me this: missing ; before statement
Solution 1:
Use an array for this.
var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}
Solution 2:
I agree it is generally preferable to use an Array
for this.
However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this
– which always refers to the current scope.
for (var i = 0; i < coords.length; ++i) {
this["marker"+i] = "some stuff";
}
You can later retrieve the stored values (if you are within the same scope as when they were set):
var foo = this.marker0;
console.log(foo); // "some stuff"
This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.
Solution 3:
Try this
window['marker'+i] = "some stuff";