Home >Web Front-end >JS Tutorial >What is the random number function in js
The random number function Math.random() in JavaScript generates a random number between 0 and 1. Other uses include: Random number within the specified range: Math.random() * (max - min) min generates an integer random number: Math.floor(Math.random() * (max - min 1)) min generates a specified number of random numbers: uses a loop to generate a specified number of random numbers
Random number function in JS
JavaScript provides a function named Math.random()
for generating A random number between 0 (inclusive) and 1 (exclusive).
Usage:
<code class="javascript">const randomNumber = Math.random();</code>
Notes:
Math.random()
will generate a new random number. Math.random()
function should not be used. Extended usage:
Random numbers within the specified range:
<code class="javascript">// 生成 [min, max] 范围内的随机数 const randomNumber = Math.random() * (max - min) + min;</code>
Generate random integers Number:
<code class="javascript">// 生成 [min, max] 范围内的随机整数 const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;</code>
Generate the specified number of random numbers:
<code class="javascript">// 生成 count 个随机数,范围为 [min, max] const randomNumbers = []; for (let i = 0; i < count; i++) { randomNumbers.push(Math.random() * (max - min) + min); }</code>
The above is the detailed content of What is the random number function in js. For more information, please follow other related articles on the PHP Chinese website!