JS can use the Math (arithmetic) object to generate random numbers.

Math Object Methods You Need to Know

Method Description
ceil(x) Rounds up a number, i.e., round up.
floor(x) Rounds x down, i.e., round down.
round(x) Rounds to the nearest integer.
random() Returns a random number between 0 and 1, including 0 but not 1.

Some example explanations:

Math.ceil(Math.random()*10);     // 获取从 1 到 10 的随机整数,取 0 的概率极小。

Math.round(Math.random());       // 可均衡获取 0 到 1 的随机整数。

Math.floor(Math.random()*10);    // 可均衡获取 0 到 9 的随机整数。

Math.round(Math.random()*10);    // 基本均衡获取 0 到 10 的随机整数,其中获取最小值 0 和最大值 10 的几率少一半。

Because the result is 0 for 0~0.4, 1 for 0.5 to 1.4, 9 for 8.5 to 9.4, and 10 for 9.5 to 9.9. So the head and tail distribution intervals are only half of the other numbers.


Generate random integers in [n,m]

Function purpose: Generate[n,m]a random integer.

Useful when generating captchas or randomly selecting an option in JS.

//生成从minNum到maxNum的随机数
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
} 

Process analysis:

Math.random() generates a number in [0,1), so Math.random()*5 generates a number in [0,5).

Usually we expect an integer, so we need to process the result.

parseInt(), Math.floor(), Math.ceil() and Math.round() can all yield integers.

parseInt() and Math.floor() both round down.

So Math.random()*5 generates random integers in [0,4].

So to generate a random number in [1,max], the formula is as follows:

// max - 期望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);

So to generate a random number from [0,max] to any number, the formula is as follows:

// max - 期望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));

So if you want to generate a random number in [min,max], the formula is as follows:

// max - 期望的最大值
// min - 期望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);

Example

// User input
const min = parseInt(prompt(Enter minimum value:));
const max = parseInt(prompt(Enter maximum value:));

// Generate a random number
const a = Math.floor(Math.random() * (max - min + 1)) + min;

// Display the random number
document.write(`${min}to ${max}random number: ${a}`);

Try it »

An online random number generator:https://c.example.com/front-end/6680/

Original link: http://www.cnblogs.com/starof/p/4988516.html