Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    trouble with nested loops

    I'm having trouble getting this nested loop to work. It only outputs the last image and I want it to loop through the images.
    Code:
    function loadgallery (){
    
    
    var picarray= new Array ()
    
    picarray[0]="pic1.jpg"
    picarray[1]="pic2.jpg"
    picarray[2]="pic3.jpg"
    picarray[3]="pic4.jpg"
    picarray[4]="pic5.jpg"
    picarray[5]="pic6.jpg"
    
    for (j=0;j<picarray.length ;j++ ){
    
    pic=picarray[j]
    
    
    
    
    var tdarray = document.getElementsByTagName("td");
    
    for (i=0;i<tdarray.length;i++ ){
     
    
        
    tdarray[i].innerHTML='<select name="select1"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option></select><img src="pics/'+picarray[j]+'">';
    
    }
    }
    
    }
    
    window.onload=loadgallery;

  • #2
    Senior Coder
    Join Date
    Sep 2010
    Posts
    2,215
    Thanks
    15
    Thanked 253 Times in 253 Posts
    I don't think you need two loops, since you're just using the items in one collection to modify the items in another collection of the same size.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,585
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Just *THINK* about what that code is doing:

    The outer FOR loop goes through all the images, one by one.

    The inner FOR loop goes through all your <TD>s, one by one.

    Each time through the *INNER* loop, you are setting *ALL* of the <TD>s to contain the image that was chosen by the outer loop.

    So when the outer loop has j=0, *ALL* the <TD>s get the image in picarray[0].
    So when the outer loop has j=1, *ALL* the <TD>s get the image in picarray[1].
    So when the outer loop has j=2, *ALL* the <TD>s get the image in picarray[2].
    So when the outer loop has j=3, *ALL* the <TD>s get the image in picarray[3].
    So when the outer loop has j=4, *ALL* the <TD>s get the image in picarray[4].
    So when the outer loop has j=5, *ALL* the <TD>s get the image in picarray[5].

    It is doing *exactly* what you asked it to do .

    In short, Dr.DOS is probably correct, but we can't really tell for sure what you are trying to do.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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