[javascript] 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

This question is related to javascript jquery google-maps

The answer is


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.


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

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

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

 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.


Try this

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api