Home > Article > Web Front-end > How to output random integers from m to n in js
In JavaScript, you can use the following steps to generate a random integer between m and n: Use Math.random() to generate a random number between 0 and 1. Multiply the result by the range (n - m 1). Round the result to an integer. Add m to the result.
How to output a random integer between m and n in JavaScript
In JavaScript, we can use Math.random()
function and range operators (...
) to generate random integers between m and n.
Steps:
Math.random()
function to generate a random number between 0 and 1. Math.floor()
) to round the result to an integer. Code example:
<code class="javascript">function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }</code>
Usage:
<code class="javascript">const randomNumber = getRandomInt(5, 10); // 输出 5 到 10 之间的随机整数 console.log(randomNumber); // 例如,输出 8</code>
The above is the detailed content of How to output random integers from m to n in js. For more information, please follow other related articles on the PHP Chinese website!