Home  >  Article  >  Web Front-end  >  How to create random integers in JavaScript

How to create random integers in JavaScript

青灯夜游
青灯夜游Original
2021-10-19 15:58:0126925browse

How to create random integers in JavaScript: 1. Use the "Math.random()" statement to generate a random decimal in the range of "0~1"; 2. Multiply the random decimal by an integer value and multiply it Expand the specified multiple; 3. Use the "Math.floor()" statement to round down the random number to get a random integer.

How to create random integers in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript provides a function that generates random decimals with a value in the range (0, 1).

Math.random(); // 0.10529863457509858

Next we will use this function to generate random integers in the specified range.

function randomRange(min, max) { // min最小值,max最大值
    return Math.floor(Math.random() * (max - min)) + min;
}

The principle is to first reduce the maximum value from the minimum value (guaranteed not to exceed the maximum value), multiply it by a random decimal, then add the minimum value (guaranteed not to be less than the minimum value), and finally take it downwards all.

To use, just pass in the minimum and maximum values ​​to be specified to the function.

console.log(randomRange(0, 1000);

How to create random integers in JavaScript

Isn’t it very simple.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to create random integers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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