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

What is the random number function in js

下次还敢
Release: 2024-05-06 10:21:15
Original
551 people have browsed it

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>
Copy after login

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>
Copy after login

Generate random integers Number:

<code class="javascript">// 生成 [min, max] 范围内的随机整数
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template