0

I am trying to build a 2*2 table of different images using javascript so that no two pictures inserted are duplicates. I am new to javascript so please help me with the following code.

I have written the diffImage function to select random images, but it displays duplicate images. I want the page to display an image only once, and in a different cell every time the page is loaded.

<html> <head> <script language=Javascript> function diffImage() { image = new Array("ball.gif","bench.gif","banner.gif", wall.gif"); whichImage = Math.floor(Math.random()*image.length); document.write('<image SRC="' +image[whichImage]+ '">'); } </script> </head> <body> <table id="newtable"/> <tr> <td> <script language="Javascript"> diffImage();</script> </td> <td> <script language="Javascript"> diffImage();</script> </td> </tr> <tr> <td> <script language="Javascript"> diffImage();</script> </td> <td> <script language="Javascript"> diffImage();</script> </td> </tr> </table> 

3 Answers 3

2

Try this:

imagelist = ["ball.gif","bench.gif","banner.gif","wall.gif"]; function diffimage() { whichImage = Math.floor(Math.random()*imagelist.length); document.write('<img src="'+imagelist[whichImage]+'" />'); imagelist.splice(whichImage,1); } 

This will remove the selected image from the list, so you won't get duplicates.

(Side-note: the probability of getting no duplicates with your current code is 3/32, or about 9%)

Sign up to request clarification or add additional context in comments.

Comments

0

Check where you defined the image array. You forgot to put quotation marks on wall.gif.

Comments

0

change the function calls to diffimage()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.