Creating a Random Number


var rand = min + Math.floor((max  min + 1) *   Math.random()); 

The random() method of the Math object calculates a pseudo-random number between 0 and 1 (excluding). However, usually you are interested in a random number between, say, 1 and 10. With a small mathematical calculation, this can be achieved. For the example, multiply the result of Math.random() by 10, effectively generating a number between 0 and 10 (excluding). If you then round this value, you get an integral number between 0 and 9 (including). Adding 1 leads to a number between 1 and 10.

The preceding code generalizes this and creates a number between min and max.




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net