SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast lauriek's Avatar
    Join Date
    Dec 2002
    Posts
    74
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript get vvariable names from array and then use

    Say I have some variables setup like so;

    Code:
    <script type='text/javascript'>
    <!--
    panelsArray = new Array("form0","form3","form4","form5","blotter");
    var blotter = new Array('36','462','762','292','block','');
    var form0 = new Array('202','55','609','185','block','');
    var form3 = new Array('948','68','301','139','block','');
    var form4 = new Array('861','655','400','158','block','');
    var form5 = new Array('0','0','805','291','block','');
    // -->
    </script>
    and I want to parse the first array and then within that loop I want to get the variable name from the 'outer' array and then reference the contents of the array with that name... I was trying to do the following but it doesn't work, I'm obviously missing something about transmogrifying the text "form0" into a variable name...

    Code:
        for(f=0;f<panelsArray.length;f++) {
            
            thisPanel = panelsArray[f];
            alert(thisPanel);
            thisPanelWidth = thisPanel[0]
            alert(thisPanelWidth);
            
        }
    Any tips much appreciated!!

    ETA the first alert correctly bings up "form0" but the second treats this as a string and alerts "f"...
    Last edited by lauriek; Oct 23, 2007 at 02:51. Reason: ETA bit

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    'form0' will only become your global form0 var if you call it as a property name of its owning object-the window in this case.

    thisPanel = window[panelsArray[f]];

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,631
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Code:
    panelsArrayNames = new Array("form0","form3","form4","form5","blotter");
    var blotter = new Array('36','462','762','292','block','');
    var form0 = new Array('202','55','609','185','block','');
    var form3 = new Array('948','68','301','139','block','');
    var form4 = new Array('861','655','400','158','block','');
    var form5 = new Array('0','0','805','291','block','');
    panelsArray = new Array(form0,form3,form4,form5,blotter);
    
        for(f=0;f<panelsArray.length;f++) {
            
            thisPanel = panelsArrayNames[f];
            alert(thisPanel);
            thisPanelWidth = panelsArray[f][0];
            alert(thisPanelWidth);
            
        }
    UNTESTED!
    Ian Anderson
    www.siteguru.co.uk


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
  •