Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 225
Philipp Bergmann Avatar asked Nov 24 '11 16:11

Philipp Bergmann


People also ask

How do you dynamically declare variables inside a loop in Python?

Use the for Loop to Create a Dynamic Variable Name in Python Along with the for loop, the globals() function will also be used in this method. The globals() method in Python provides the output as a dictionary of the current global symbol table.

Can you create a variable in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.


3 Answers

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
    markers[i] = "some stuff";
}
like image 94
JohnP Avatar answered Oct 11 '22 07:10

JohnP


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.

like image 20
Todd Ditchendorf Avatar answered Oct 11 '22 07:10

Todd Ditchendorf


Try this

window['marker'+i] = "some stuff"; 
like image 26
Safiq Avatar answered Oct 11 '22 08:10

Safiq