1

I want to display 2 random images on a page with no repetition. I am able to display random images but with repetition using the following code.

function ranImage() {

   picture = new Array(" array of pictures");
   whichImage = Math.floor(Math.random()*picture.length);
   document.write('<LMG SRC="' +picture[whichImage]+ '">');

}

Need Help Thanks

2 Answers 2

1

If that's all you're doing, you can pop the already displayed images out of your array.

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

2 Comments

...by just adding the line picture.splice(whichImage, 1) at the end of your function.
splice is exactly the way to go.
0

You need to save which ones you did show already. This one will work until exhausted all the images:

var alreadyShown = new Array();

function ranImage() {

picture = new Array(" array of pictures");

for (picture.length != alreadyShown; whichImage = Math.floor(Math.random()*picture.length); arr.indexOf(whichImage) == -1){
   alreadyShown[alreadyShown.length+1] = whichImage;
}

document.write('<LMG SRC="' +picture[whichImage]+ '">');

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.