Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2002
    Location
    Los Angeles
    Posts
    89
    Thanks
    0
    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.

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

  • #2
    Senior Coder A1ien51's Avatar
    Join Date
    Jun 2002
    Location
    Between DC and Baltimore In a Cave
    Posts
    2,717
    Thanks
    1
    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

    so

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

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

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint]


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •