www.webdeveloper.com
Results 1 to 5 of 5

Thread: Javascript Dynamic variables names

  1. #1
    Join Date
    Sep 2010
    Posts
    15

    Javascript Dynamic variables names

    I'm trying to create variable names on the fly in a for loop, something like below:

    for i = 0; i<data.rows.length; i ++ {
    var a + data.rows.[i].c[1].v = ' some value';
    var b + data.rows.[i].c[1].v = ' some value';
    var c + data.rows.[i].c[1].v = ' some value';
    }

    My goal is to have the variable names like:
    a1234 = 'some value';
    b1234 = 'some value';
    c1234 = 'soome value';

    I keep getting error messages though. Does anyone have a good solution? Thanks!

  2. #2
    Join Date
    Sep 2012
    Location
    Germany
    Posts
    22
    try an object like this:

    HTML Code:
    var results = {};
    
    for i = 0; i<data.rows.length; i ++ {
      results[a + data.rows.[i].c[1].v] = ' some value';
      results[b + data.rows.[i].c[1].v] = ' some value';
      results[c + data.rows.[i].c[1].v] = ' some value';
    }
    console.log(results);
    console.log(results[a1234]);
    console.log(results.a1234);

  3. #3
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    1,031
    I don't know that you can create actual named variables on-the-fly in javascript. And even if it can be done (though not likely), there is a better way to go about this.

    Objects (and arrays for that matter) are lovely things in javascript as they allow you to store a great deal of information in a very organized manor.
    Code:
    var $onTheFly = {};
    for(i = 0; i<data.rows.length; i++){
    	$onTheFly["a" + data.rows.[i].c[1].v] = ' some value';
    	$onTheFly["b" + data.rows.[i].c[1].v] = ' some value';
    	$onTheFly["c" + data.rows.[i].c[1].v] = ' some value';
    }
    console.log($onTheFly["a1234"]); // Prints "some value" to the console
    Also, I'm not sure if this is just a matter of how you posted your code on the forum or not, but you don't appear to have any parentheses around your for() loop parameters. Someone could correct me if I'm wrong but I'm fairly certain those are required (and thus would create an error otherwise).

  4. #4
    Join Date
    Sep 2012
    Location
    Germany
    Posts
    22

  5. #5
    Join Date
    Sep 2010
    Posts
    15
    Thank guys!!! Using an object to store data worked great for me. And I did have parentheses around the for loop, just typed it in wrong.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles