SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    creating a variable from a string

    Hi,

    Is there any way to build a variable name and declare it from a string.

    say i have a for loop and i want to build a variable called: droppable_x .....where x is the iterable. So i'd want a variable called droppable_x. Can i do this?

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    var varName = "droppable_x";
    window[varName] = 42;
    alert(droppable_x);
    Birnam wood is come to Dunsinane

  3. #3
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    In the for loop:
    Code javascript:
    for (var i = 0; i < stuff.length; i++) {
      window['droppable_' + i] = i * 2;
    }
    alert(droppable_4); // 8

  4. #4
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    aha nice one guys

  5. #5
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Acutally when i do that i get a missing ; before statment on the var window line:

    Code JavaScript:
    var strings = textAreaContents.split('\n');
    			var formatted = '';
    			for(var i=0; i < strings.length; i ++) {
    			    var window['string_' + i] = strings[i];
    			}

  6. #6
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    dont put var before window


Bookmarks

Posting Permissions

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