Home  >  Article  >  Web Front-end  >  How to get random integers in js

How to get random integers in js

下次还敢
下次还敢Original
2024-05-06 10:09:18662browse

There are many ways to get random integers in JavaScript, including: using Math.floor(Math.random() * (max - min 1)) min: generate between min and max (inclusive) of random integers; use Crypto.getRandomValues(): Generate safer random integers between min and max (inclusive).

How to get random integers in js

How to get random integers in JavaScript

There are many ways to get random integers in JavaScript, please choose Which approach depends on specific needs.

Math.floor(Math.random() * (max - min 1)) min

The most common method is to use Math.random() and Math.floor() Function:

  • Math.random() Returns a value between 0 (inclusive) and 1 (exclusive) ).
  • Math.floor() Round the floating point number down.

Multiply Math.random() by max - min 1, you can get a value between min and A random floating point number between max (inclusive). Then use Math.floor() to round the floating point number down to get an integer. min and max are the minimum and maximum values ​​of the random integers to be generated.

Example:

<code class="js">// 生成一个介于 0 和 9(含)之间的随机整数
let randomInteger = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
console.log(randomInteger); // 输出:介于 0 和 9 之间的随机整数</code>

Crypto.getRandomValues()

For cases where more secure random integers are required, you can use Crypto.getRandomValues() Method:

  • window.crypto.getRandomValues() Returns a Uint8Array containing a random byte array .

You can use the fromArrayBuffer() method to convert Uint8Array to an integer:

Example:

<code class="js">// 生成一个介于 100 和 999(含)之间的随机整数
let buffer = new ArrayBuffer(4);
window.crypto.getRandomValues(buffer);
let int = new DataView(buffer).getUint32(0);
let min = 100;
let max = 999;
let randomInteger = int % (max - min + 1) + min;
console.log(randomInteger); // 输出:介于 100 和 999 之间的随机整数</code>

The above is the detailed content of How to get random integers 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