Home > Web Front-end > JS Tutorial > body text

js method to calculate random numbers between arbitrary values_javascript skills

WBOY
Release: 2016-05-16 16:19:58
Original
963 people have browsed it

The example in this article describes how js calculates random numbers between arbitrary values. Share it with everyone for your reference. The specific implementation method is as follows:

First of all: Math.random() is a method that calculates random numbers and returns random numbers that are greater than or equal to 0 and less than 1,

Math.random()*10 doesn’t return a number greater than or equal to 0 and less than 10, but it can only return a number less than 10 and cannot return 10. What should we do? We add 1 to the original function and it becomes It 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, which does not meet the requirements. The Math.floor() function is used below. This The function performs downward rounding, which means that 10.99 is always 10 after passing through Math.floor. Even if Math.ceil (rounded upward) is 10.00001, the return value is 11. Now we can find the result:

Copy the code The code is as follows:
Math.floor(Math.random()*10 1);
This way you can get the result .

What about the functions between 2 and 10? Directly enter the code

Copy the code The code is as follows:
Math .floor(Math.random()*9 2);

What about 3 to 11, and 4 to 88? There is no way to calculate it by yourself every time. Here is a general method for everyone;

Copy code The code is as follows:
function selectfrom (lowValue,highValue){
var choice=highValue-lowValue 1;
return Math.floor(Math.random()*choice lowValue);
}

Then just adjust the above method and it’s OK

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template