faqts : Computers : Programming : Languages : JavaScript : Language Core : Math

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

34 of 43 people (79%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How to get a random index to an Array?
How to get a random index to an Array?

Feb 7th, 2000 03:15
Martin Honnen,


Often you want to randomly index an array (for a random quote for 
example). The JavaScript built in 
  Math
object has a
  Math.random
function producing a (pseudo) random numbers between 0 and 1. By 
multiplying with the array length and using Math.floor to truncate to 
integer you get a random index into the array. Example

var a = new Array ('Kibology for all', 
                   'All for Kibology', 
                   'Scriptology for all');
var randomIndex = Math.floor(Math.random() * a.length);
alert(a[randomIndex])