This article mainly introduces how to calculate random numbers between arbitrary values in js and analyzes Math. the usage skills of the random function have some reference value. If you need it, you can refer to the examples in this article to describe how to calculate random numbers between any values in js. Share it with you for your reference. The specific implementation method is as follows:
First, the Math. random () method is used to calculate a random number and return a random number greater than or equal to 0 and less than 1,
Math. random () * 10 isn't it true that the return value is greater than or equal to 0 and less than 10, but he can only return a number smaller than 10, and cannot return 10? What should I do, we add 1 to the original function and it becomes Math. random () * 10 + 1; now we can return a random number ranging from 1 to 10, but we return many decimal places, which do not meet the requirements. Math is used below. floor () Is the function, which is rounded down, that is, 10.99 passes through Math. all floors are 10, Math. ceil (rounded up) returns 11 even if it is 10.00001. Now we can find the result:
The Code is as follows:
Math. floor (Math. random () * 10 + 1 );
In this way, the result can be obtained.
What about the functions between 2 and 10?
The Code is as follows:
Math. floor (Math. random () * 9 + 2 );
So what about 3 to 11 and 4 to 88? Every time this is done, it is not a solution. Next we will introduce a general method;
The Code is as follows:
Function selectfrom (lowValue, highValue ){
Var choice = highValue-lowValue + 1;
Return Math. floor (Math. random () * choice + lowValue );
}
Then directly adjust the above method to OK
I hope this article will help you design javascript programs.