1. Preparation knowledge
(); //From it upwards. (); //From downwards. (); //rounding. (); // A pseudo-random number between 0.0 ~ 1.0. 【Contains 0 and not 1】 //For example, 0.8647578968666494 (()*10); // Get a random integer from 1 to 10, and the probability of getting 0 is extremely small. (()); //The random integers from 0 to 1 can be obtained evenly. (()*10); //The random integers from 0 to 9 can be obtained balancedly. (()*10); //Basic equalization gets a random integer from 0 to 10, where the chance of getting the minimum value 0 and maximum value 10 is half the less.
Because the result is 0 between 0~0.4, 0.5 to 1.4 is 1...8.5 to 9.4 is 9, and 9.5 to 9.9 is 10. Therefore, the distribution interval between the head and tail is only half of the other numbers.
2. Generate random integers of [n,m]
Function function: generates random integers of [n,m].
It is useful when js generates verification code or randomly selects an option. .
//Generate random number from minNum to maxNumfunction randomNum(minNum,maxNum){ switch(){ case 1: return parseInt(()*minNum+1,10); break; case 2: return parseInt(()*(maxNum-minNum+1)+minNum,10); break; default: return 0; break; } }
Process analysis:
() generates a number of [0,1), so ()*5 generates a number of {0,5).
It is usually expected to get integers, so you need to process the result.
parseInt(), (), () and () can all get integers.
parseInt() and () results are both rounded downwards.
So ()*5 generates random integers of [0,4].
So the random number of [1,max] is generated, and the formula is as follows:
// max - the expected maximum valueparseInt(()*max,10)+1; (()*max)+1; (()*max);
So generate a random number of [0,max] to any number, and the formula is as follows:
// max - the expected maximum valueparseInt(()*(max+1),10); (()*(max+1));
So I hope to generate a random number of [min,max], the formula is as follows:
// max - the expected maximum value// min - Minimum value expectedparseInt(()*(max-min+1)+min,10); (()*(max-min+1)+min);
The above is a comprehensive analysis of js generating random numbers, which is very detailed, and I hope it can help everyone.