View Single Post
Old Mar 7th, 2008, 5:59 PM   #3
grimpirate
King of Portal
 
grimpirate's Avatar
 
Join Date: Sep 2005
Posts: 403
Rep Power: 3 grimpirate is on a distinguished road
Send a message via Yahoo to grimpirate
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.
__________________
Lo, there do I see my father. 'Lo, there do I see My mother, and my sisters, and my brothers. 'Lo, there do I see The line of my people... Back to the beginning. 'Lo, they do call to me. They bid me take my place among them. In the halls of Valhalla... Where the brave... May live... ...forever.. GrimBB | Mimesis
grimpirate is offline   Reply With Quote