This article mainly introduces the method that JS calculates random number between arbitrary value, analyzes the use skill of math.random function, has certain reference value, the friend who needs can refer to
This paper illustrates the method of calculating random number between arbitrary values by JS. Share to everyone for your reference. The implementation methods are as follows:
First: The Math.random () method is to compute random numbers that return greater than or equal to 0 less than 1.
Math.random () *10 not return is greater than or equal to 0 return less than 10, but he can only return less than 10 of the number, can not return 10, how to do, we add 1 on the original function into the math.random () *10+1; You can return a random number from 1 to 10 at this point, but we're returning a lot of decimals, not meeting the requirements, and we're using the Math.floor () function, which performs rounding down, That is to say 10.99 after Math.floor are 10,math.ceil (rounded up) even if 10.00001, return is 11, now we are finding the result:
The code is as follows: Math.floor (Math.random () *10+1); So we can find the result.
What about the 2 to 10 function, directly on the code
The code is as follows: Math.floor (Math.random () *9+2);
That 3 to 11, 4 to 88, each time such a calculation is not a way, the following to introduce a common method;
The code is as follows: function Selectfrom (lowvalue,highvalue) {
var choice=highvalue-lowvalue+1;
Return Math.floor (Math.random () *choice+lowvalue);
}
And then directly adjust the above method ok
I hope this article will help you with your JavaScript programming.