Philipp Bergmann
Philipp Bergmann

Reputation: 1003

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

Upvotes: 95

Views: 282740

Answers (9)

Rajaruban Rajindram
Rajaruban Rajindram

Reputation: 996

Using ES6 method. No array needed

for (let i = 1; i < coords.length; i++){
 eval(`var marker${i} = 'some stuff';`);
}

Upvotes: 0

nano dev
nano dev

Reputation: 433

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();

Upvotes: 0

vikram prajapat
vikram prajapat

Reputation: 1

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

Upvotes: -3

Todd Ditchendorf
Todd Ditchendorf

Reputation: 11337

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.

Upvotes: 60

Md Junaid Alam
Md Junaid Alam

Reputation: 1349

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);
}

Upvotes: 2

kayleeFrye_onDeck
kayleeFrye_onDeck

Reputation: 6958

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]  */
}

Upvotes: 17

JohnP
JohnP

Reputation: 50019

Use an array for this.

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

Upvotes: 136

Safiq
Safiq

Reputation: 239

Try this

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

Upvotes: 23

Alfgaar
Alfgaar

Reputation: 172

 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.

Upvotes: -7

Related Questions