JavaScript for loop question

Hi,

I have a simple image gallery script like the following:

var i = 2;
var img = new Array(i);
img[0] = new Image();
img[1] = new Image();
img[2] = new Image();
img[0].src = "images/slide1.jpg";
img[1].src = "images/slide2.jpg";
img[2].src = "images/slide3.jpg";
var num = 0;
function previous(){
	num--;
	if(num < 0){ num = i; }
	document.slider.src = img[num].src;
}
function next(){
	num++;
	if(num > i){ num = 0; }
	document.slider.src = img[num].src;
}

I want to use a for loop so that when I want to add more images, I will just change “i” and it will work ok.

Here is what I am trying but it seems not to work:

var i = 2;
var img = new Array(i);
for (n=0;n<=i;n++) {
	img[n] = new Image();
	img[n].src = "images/slide".n.".jpg";
}
var num = 0;
function previous(){
	num--;
	if(num < 0){ num = i; }
	document.slider.src = img[num].src;
}
function next(){
	num++;
	if(num > i){ num = 0; }
	document.slider.src = img[num].src;
}

Do you have an idea what I am doing wrong? Thanks.

The only issue i can see is the way you wrote the src line in your loop, see the below which is highlighted in red.

img[n].src = "images/slide[B][COLOR=#ff0000]".n."[/COLOR][/B].jpg";

In JavaScript you need to use the + sign, currently you have it written as though you were coding in PHP.

img[n].src = "images/slide" + n + ".jpg";

Thanks Chris, just learning JS. I changed that line, but I also had to change some other parts. I think it shouldn’t be necessary to change other parts because all I did was to put the image definitions into a for loop. Here is my final code that works:

var i = 3;
var img = new Array(i);
for (n=0;n<=i;n++) {
	img[n] = new Image();
	img[n].src = "images/slide" + n + ".jpg";
}
var num = 1;
function previous(){
	num--;
	if(num < 1){ num = i; }
	document.slider.src = img[num].src;
}
function next(){
	num++;
	if(num > i){ num = 1; }
	document.slider.src = img[num].src;
}