How do I create dynamic variable names inside a loop?

JavascriptJqueryGoogle Maps

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
    markers[i] = "some stuff";
}

Solution 2 - Javascript

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 - Javascript

Try this

window['marker'+i] = "some stuff"; 

Solution 4 - Javascript

In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays and dynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval() is even another option.

v0 = "Variable Naught";
v1 = "Variable One";

for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
  dyV = eval(`v${i}`);
  console.log(`v${i}`); /* => v0;   v1;  */      
  console.log(dyV);  /* => Variable Naught; Variable One;  */
}

When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval() to get the value is kind of lame when you're used to getting it automatically.

_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}]    //Array of Object(s)


for (i = 0; i < 3; i++)
{
  console.log(`_${i}`);           /*  var
                                   * =>   _0  _1  _2  */

  console.log(`"_${i}"`);         /*  var name in string  
                                   * => "_0"  "_1"  "_2"  */

  console.log(`_${i}` + `_${i}`); /*  concat var with var
                                   * => _0_0  _1_1  _2_2  */

  console.log(eval(`_${i}`));     /*  eval(var)
                                   * => My first variable
                                        Object {key_0: "value_0"}
                                        [Object]  */
}

Solution 5 - Javascript

You can use eval() method to declare dynamic variables. But better to use an Array.

for (var i = 0; i < coords.length; ++i) {
    var str ="marker"+ i+" = undefined";
    eval(str);
}

Solution 6 - Javascript

In this dynamicVar, I am creating dynamic variable "ele[i]" in which I will put value/elements of "arr" according to index. ele is blank at initial stage, so we will copy the elements of "arr" in array "ele".

function dynamicVar(){
            var arr = ['a','b','c'];
            var ele = [];
            for (var i = 0; i < arr.length; ++i) {
                ele[i] = arr[i];
 ]               console.log(ele[i]);
            }
        }
        
        dynamicVar();

Solution 7 - Javascript

var marker  = [];
for ( var i = 0; i < 6; i++) {				 
	 marker[i]='Hello'+i;					 
}
console.log(marker);
alert(marker);

Solution 8 - Javascript

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilipp BergmannView Question on Stackoverflow
Solution 1 - JavascriptJohnPView Answer on Stackoverflow
Solution 2 - JavascriptTodd DitchendorfView Answer on Stackoverflow
Solution 3 - JavascriptSafiqView Answer on Stackoverflow
Solution 4 - JavascriptkayleeFrye_onDeckView Answer on Stackoverflow
Solution 5 - JavascriptMd Junaid AlamView Answer on Stackoverflow
Solution 6 - Javascriptnano devView Answer on Stackoverflow
Solution 7 - Javascriptvikram prajapatView Answer on Stackoverflow
Solution 8 - JavascriptAlfgaarView Answer on Stackoverflow