Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   JavaScript and Client-Side Browser Scripting (http://www.programmingforums.org/forum23.html)
-   -   Random image array (http://www.programmingforums.org/showthread.php?t=15363)

Smessed-Up Mar 7th, 2008 4:53 AM

Random image array
 
basically once one of the images is created randomly i want it removed from the array so it cant come up again but for some reason not all the images are appearing anyway heres what ive got whats wrong/missing?

[code]var image=new Array();
var g='.gif';
image[0]='image1'+g;
image[1]='image2'+g;
image[2]='image3'+g;
image[3]='image4'+g;
image[4]='image5'+g;
var l=image.length;
var buff=new Array();
for(i=0;i<l;i++){

buff[i]=new Image();
buff[i].src=image[i];

}

var randomNumber=Math.floor(Math.random()*l);
for(i=0;i<l;i++){

document.write('<img src="'+image[randomNumber]+'">');
image.splice(randomNumber,1);

}

grimpirate Mar 7th, 2008 5:38 PM

Re: Random image array
 
If you want to display all 5 images it's easier just to do the following:
:

<script type="text/javascript">
<!--
        for(var i = 0; i < 5; i++) {
                document.write('<img src="image"' + (i + 1) + '.gif">');
        }
//-->
</script>

Also be sure to properly enclose your code in code tags.

grimpirate Mar 7th, 2008 5:59 PM

Re: Random image array
 
If you want them to appear in a random order, for whatever reason:
:

<script type="text/javascript">
<!--
        var imgCount = 5;
        var image = new Array();
        for(var i = 0; i < imgCount; i++) {
                image.push('image' + (i + 1) + '.gif');
        }
        while(image.length > 0){
                var randomIndex = Math.floor(Math.random() * image.length);
                document.write('<img src="' + image[randomIndex] + '" alt="' + image[randomIndex] + '">');
                image.splice(randomIndex, 1);
        }
//-->
</script>

The issue with your code is that when you splice the array you're not taking into account the fact that the array size is changing dynamically. Therefore, you're generating non-existent indices. Whenever you splice an array you're going to be shortening its length, and the result will have new indices. Thus, when you have 5 elements your random number generation needs to be from 0 to 4, when you remove one and have 4 elements it needs to be from 0 to 3, and so on, until you have no more elements left in the array.

Smessed-Up Mar 7th, 2008 7:40 PM

Re: Random image array
 
Ah i see now thankyou for your help.


All times are GMT -5. The time now is 3:49 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC