Home  >  Article  >  Web Front-end  >  What is the random number function in js

What is the random number function in js

下次还敢
下次还敢Original
2024-05-06 10:21:15338browse

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

What is the random number function in js

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:

  • The random numbers generated are all floating point numbers.
  • Each call to Math.random() will generate a new random number.
  • Although the generated random numbers look random, they are actually generated based on a pseudo-random number generation algorithm.
  • For situations where truly random numbers are required (such as cryptography), the 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!

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