This article describes the method of JS to calculate random numbers between arbitrary values. Share it for your reference. The specific implementation method is as follows:
First of all: Math.random() method is to calculate the random number return a random number greater than or equal to 0 or less than 1.
Doesn't Math.random()*10 return more than or equal to 0 and return less than 10? But it can only return numbers less than 10, but it cannot return 10. What should we do? Adding 1 to the original function becomes Math.random()*10+1; at this time, we can return random numbers from 1 to 10, but many of the numbers we return are decimals and do not meet the requirements. The following is the function Math.floor(). This function performs rounding down, which means that after 10.99, it is 10, and Math.ceil (which is rounding up) even if it is 10.00001, it returns 11. Now we find the result: the code copy is as follows: Math.floor(Math.random()*10+1); this way you can find the result.
What should I do if the functions between 2 and 10 are directly copied into the code and the code is as follows: Math.floor(Math.random()*9+2);
From 3 to 11, from 4 to 88, it is not a solution to calculate it yourself every time. Here is a general method to introduce to you;
The code copy is as follows: function selectfrom (lowValue, highValue){
var choice=highValue-lowValue+1;
return Math.floor(Math.random()*choice+lowValue);
}
Then adjust the above method directly
I hope this article will be helpful to everyone's JavaScript programming.