Computer >> Computer tutorials >  >> Programming >> Javascript

How do I create dynamic variable names inside a JavaScript loop?


To achieve this, you need to add properties to the current scope. Achieve this using this, which is for the current scope in the program −

for (var i = 0; i < coords.length; ++i) {
   this["marker"+i] = "add here";
}

The above will get what you want and retrieve it like the following −

var a = this.marker0;
alert(a);

It will give you the text “add here” as shown above.