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 3 of 3
  1. #1
    Senior Coder
    Join Date
    Aug 2002
    Location
    UK
    Posts
    2,789
    Thanks
    2
    Thanked 14 Times in 14 Posts

    Randomly referencing array index

    When randomly referencing an arrays index which is the best method to use.

    Math.round(Math.random()*5)

    or

    Math.floor(Math.random()*5)

    with an array set out as follows

    array_name=new Array()

    array_name[0]=""
    array_name[1]=""
    array_name[2]=""
    array_name[3]=""
    array_name[4]=""

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    Nashua, NH
    Posts
    1,724
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Array.prototype.getRandom = function()
    { return this[Math.floor(Math.random()*this.length)];
    }
    Vladdy | KL
    "Working web site is not the one that looks the same on common graphical browsers running on desktop computers, but the one that adequately delivers information regardless of device accessing it"

  • #3
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Math.round gives half probability to either of the top/bottom choices. Math.floor and Math.ceil are better, since the probability of a return value ofexactly 1 and 0 from Math.random, respectively, is so infinitely small ((2^64 - 2^54)^-1, if you want to know) that it's almost impossible. However, multiplying with a large number and then calculating the modulo of the array length would eliminate even that small chance.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards


  •  

    Posting Permissions

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