Our aim is to randomly display a text string from a set. It involves the following steps
var text_st = new Array("String1", "String2", "String3", "String4", "String5", "String6", "String7", "String8", "String9", "String10"); var l = text_st.length; var rnd_no = Math.floor(l*Math.random()); alert(text_st[rnd_no]);
Note: Array are zero-indexed, thus, we can use the value of variable l (length of the array) directly because we are using floor() to round down to an integer.
I have used this code on several web sites to display a random testimonial from a set. So each time the web page loads a testimonial is selected and displayed at random. The code can also be used to display a random quote or a greeting.
The World Wide Web Hall of Fame has only 6 inductees: Tim Berners-Lee: Inventor of the World Wide Web. Marc Andreessen: Co-creator of Mosaic, the browser that popularised the web. Eric Bina: Co-creator of Mosaic browser and founder of Netscape. Kevin Hughes: A pioneer of the WWW in the US. Rob Hartill: Known for his contributions to the Apache web server and the Internet Movie Database (IMDb). Lou Montulli: Co-creator of Lynx text web browser who innovated several browser technologies like cookies, HTTP proxying etc. [more...]