View Full Version : Random selection question

12-31-2003, 04:02 AM
I have a question about the below code. In regards to the variable set as randomNumber. It can return either a 0 or 1. Why would it return a 1 or a 0? I must not have a good understanding of Math.random than. Does a random only work with an array larger than 1. The array use to be larger than 1, but modifications were made that it became one. When it became one, the random returns both 0 and 1 which is what I don't understand.

testText = new Array();
testText[0] = "http://www.codingforums.com/images/icons/icon5.gif";
var randomNumber = Math.floor(Math.random()*testText.length);


Thanks in advance.

12-31-2003, 03:14 PM
Random returns a decimal number between 0 and 1

The problem you are facing is you are using length so you need to subtract 1 from it so it works with the array since it starts at 0


var randomNumber = Math.floor(Math.random()*(testText.length - ));

That will always return zero like you want it to....Hope that explained it for you.