Home >Web Front-end >JS Tutorial >How to create random integers in JavaScript
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.
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);
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!