The usage and related functions of generating random Numbers in JS
- 2020-11-26 18:40:47
- OfStack
First, I will introduce some functions related to random Numbers:
var Rand = Math.random();
Math: Mathematical object that provides mathematical calculations of data.
Math.random(); Returns 1 random number between 0 and 1 (including 0, not including 1).
Math.ceil(n); Returns the smallest integer greater than or equal to n.
Use Math. ceil (Math random (10); , mainly getting random integers from 1 to 10, with a very small chance of getting 0.
Math.round(n); Returns the value of an integer rounded off from n4.
Use Math. round (Math random ()); Random integers from 0 to 1 can be equalized.
Use Math. round (Math random (10); , the random integer from 0 to 10 can be obtained by basic equilibrium, and the probability of obtaining the minimum value of 0 and the maximum value of 10 is less than 1 half.
Math.floor(n); Returns the largest integer less than or equal to n.
Use Math. floor (Math random (10); , a random integer from 0 to 9 can be equalized.
Random sweepstakes are also extensible, such as setting the probability of sweepstakes, and using database 1.
// The probability of winning, 100% Winning the lottery, 3 Item prize, but the probability of getting a book is zero 20%
function draw() {
var d_s = GetRandom(100);
if (d_s >= 1 && d_s <= 40) {
alert(' Congratulations on your drawing XXX ! ');
} else if (d_s >= 41 && d_s <= 80) {
alert(' Congratulations on your drawing XXX ! ');
} else {
alert(' Congratulations on getting the book! ');
}
}
Corresponding function code of js to generate random Numbers:
<script>
2function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
8var num = GetRandomNum(1,10);
9alert(num);
</script>
var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
function generateMixed(n) {
var res = "";
for(var i = 0; i < n ; i ++) {
var id = Math.ceil(Math.random()*35);
res += chars[id];
}
return res;
}
Above is the detailed content of this article, hope to be helpful to your study.