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])