1) Generating a random number
We make use of the Math 'class' available in Javascript
var randomvar = Math.random();The result is a decimal number e.g. 0.43209418.
2) Generating a random number with a given range
Say for example, we want a random number to be generated from 1 - 10.
var randomvar = Math.random();
var roundedvar = Math.round(randomvar*10);
Same logic if you want a number from 1 to 1000.
var randomvar = Math.random();
var roundedvar = Math.round(randomvar*1000);
3) What if I want a value from a minimum of 5 to 10, instead of 1 to 10?
This involves a bit of logic and mathematics...
First, we need a random generated value.
Then, we multiply this random generated value with the difference of the range boundaries (e.g. randomvalue * (max - min) ).
Finally, we add the rounded value obtained in step 2 with the minimum value.
Not convinced? See code for randomNum function below and try if for yourself:
function randomNum(min,max)
{
var randomvar = Math.random() * (max - min);
var roundedvar = Math.round(randomvar) + min;
alert( roundedvar);
}
No comments:
Post a Comment