...

View Full Version : trouble with nested loops



rycon
11-15-2010, 05:31 AM
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.


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;

DrDOS
11-15-2010, 05:29 PM
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.

Old Pedant
11-15-2010, 08:17 PM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum