Arrays of Pictures

Why put pictures in an array?

  1. You can "preload" the pictures, to save time in retransmission from server. (Extra credit for a "formal" empirical study and analysis of the conditions under which time is saved and the conditions under which image caching by browser does not occur. If you don't know what is meant by a "formal empirical study" you are advised not to undertake this analysis.)
  2. Reference through an array simplifies naming of the pictures.
  3. The image tags on the page are put in an array anyway. (Document.images[])

Mechanics:

Let's say you have ten pictures all in the same directory somewhere.:

r1.jpg (4308 bytes) r2.jpg (4662 bytes) r3.jpg (3714 bytes) r4.jpg (4014 bytes) r5.jpg (3987 bytes) r6.jpg (3971 bytes) r7.jpg (4123 bytes) r8.jpg (3774 bytes) r9.jpg (3919 bytes) r10.jpg (4270 bytes)
r/r1.jpg r/r2.jpg r/r3.jpg r/r4.jpg r/r5.jpg r/r6.jpg r/r7.jpg r/r8.jpg r/r9.jpg r/r10.jpg

Images excerpted from Webster's New International Dictionary of the English Language, 1911.

To load the images in an array involves work such as the following:

JavaScript description
pix=new Array(10);
create a new array of ten elements.
pix[0]=new Image;
pix[0].src="r/r1.jpg";
pix[1]=new Image;
pix[1].src="r/r2.jpg";
pix[2]=new Image;
pix[2].src="r/r3.jpg";
  .
  .
  .
pix[9]=new Image;
pix[9].src="r/r10.jpg";
let each element of the array be an Image object with source defined by a string that refers to a file containing a picture.

If the files containing the 10 images are named with consecutive numbers, then we may streamline the process through a loop:

JavaScript description
pix=new Array(10);
create a new array of ten elements.
for (i=0;i<10;i++){
    pix[i]=new Image;
    pix[i].src="r/r"+(i+1)+".jpg";
}
let each element of the array be an Image object with source defined by a string that refers to a file containing a picture.

The above "selection" object is driven quite simply by:

<select name="u" size="3" onchange="p.src=pix[u.value-1].src">
...
<img src="p1.jpg" name="p">