Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: Random selection question
12-31-2003, 05:02 AM #1
- Join Date
- Jul 2002
- Los Angeles
- Thanked 0 Times in 0 Posts
Random selection question
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 = "http://www.codingforums.com/images/icons/icon5.gif"; var randomNumber = Math.floor(Math.random()*testText.length); %> <%=testText[randomNumber]%>
12-31-2003, 04:14 PM #2
- Join Date
- Jun 2002
- Between DC and Baltimore In a Cave
- Thanked 94 Times in 88 Posts
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.