|
Partners
|
|
| Method | Description |
| random() | Returns a random number between 0 and 1, although the number returned is usually in between, in the form of 0.xxxxxxxxxxxxxxxxx |
| round(num) | Returns the specified number rounded to the nearest integer. |
Lets break down these methods now.
The random() method of the Math object returns a random number between 0 and 1, although its important to realize that this number is usually in between, (0.xx..., with 17 decimals). The random() method ultilizes the clock in the client's computer to generate this number. Lets see it in action:
<form> <input type="button" value="random number" onClick="alert(Math.random())"> </form>
Click on the above example multiple times; the number alerted will be different each and every time. Notice the syntaz:
Math.random()
The first letter of "Math" HAS to be capitalized if you don't want to end up banging your keyword against the desk!
We now know in general how to generate a random number in JavaScript.
A random number with 17 decimal points can be quite hard to work with...here's where the round() method comes in. The round() method of the Math object rounds any given number to the nearest interger. Here are a few simple examples:
Math.round(3.4564) //returns 3 Math.round(3.6) //returns 4 Math.round(234.342) //returns 234
We now have all the tools we need to simulate randomness!