Click to See Complete Forum and Search --> : just a one "for"


chef
11-23-2002, 06:29 PM
Hi,

in my JavaScript i need the following lines ...

pic1.src=bild[num].src;
pic2.src=bild[num+1].src;
pic3.src=bild[num+2].src;
pic4.src=bild[num+3].src;
pic5.src=bild[num+4].src;
pic6.src=bild[num+5].src;
pic7.src=bild[num+6].src;

Can i somehow use "for" to shorten it, like e.g.

anzahl=7
for (var i=1;i<=anzahl;i++) { pic1.src=bild[num+(i-1)].src; }

the problem is, i also need to replace the "1" in the
pic1, pic2, pic3 ... part

How can I do this ?

cu
Philip

MikeOS
11-23-2002, 07:41 PM
Ok, I don't know what you want to do this for so I can only help so much!!

<script language="javascript">
var i;
var newarray = new Array()

for (i = 1; i <= 7; i++)
{
if (i == 1)
{
newarray[i] = "pic" + i + ".src=bild[num].src;"
}
else
{
newarray[i] = "pic" + i + ".src=bild[num+" + (i - 1) + "].src;"
}
}
</script>

Ok this formulates those lines you want into strings. The reason the for loop contains an if, else pair is because of the naming convention you have used. The first one doesn't contain a number next to num:

pic1.src=bild[num].src;

If that contained zero, then this code could be altered, and made shorter, so as to exclude the if, else pair.

If I knew exactly what it is you were doing I may be able to help you better, as it stands this forms what you wanted into a series of strings stored in an array. You can see this if you run the code below (after the code above of course):

var j;
for (j=1; j < newarray.length; j++)
{
document.write(newarray[j] + "<br>")
}

chef
11-24-2002, 04:58 AM
a picture changing script:

<script language="JavaScript">
<!--
bild = new Array();
anzahl=7;
for (var i=1;i<=anzahl;i++) { bild[i] = new Image(); bild[i].src = "fotos/1x1.gif"; }
for (i=anzahl+1;i<=2*anzahl;i++) { bild[i] = new Image(); bild[i].src = "fotos/toscana/0"+(i-anzahl)+".gif"; }
num=1;
maxpix=14;

function changer(status)
{
if(status=="showhide") { num=num+anzahl; }

if(num<=0){ num=1; }
if(num>maxpix){ num=maxpix; }

for (i=1;i<=anzahl;i++) { pic1.src=bild[num+(i-1)].src; }
}


so all the for-part belongs to the script ...
so, can i do better the zero for i=0 ... shouldn't be a problem
i could just add "+1" in the num-part.

was that any help ?

Charles
11-24-2002, 06:19 AM
The following might work:

for(i=1,n=num;i<=7;i++,n++) {eval('pic'+i+'=build[n].src')}

chef
11-24-2002, 07:45 AM
the eval()-thing ;-)

seems to be what i was looking for ...
thank you

Charles
11-24-2002, 07:51 AM
I thought it might be. You are quite welcome.