Home > Web Front-end > JS Tutorial > How Can I Generate Unique Random Numbers Within a Specific Range in JavaScript?

How Can I Generate Unique Random Numbers Within a Specific Range in JavaScript?

Barbara Streisand
Release: 2024-12-09 22:21:18
Original
959 people have browsed it

How Can I Generate Unique Random Numbers Within a Specific Range in JavaScript?

Generating Unique Random Numbers Within a Specific Range Using JavaScript

The task at hand is to devise a method in JavaScript that generates a series of distinctive random integers within a designated range (in this case, 1 to 100). To achieve this, we can leverage the following approach:

Using the JavaScript Math.random() function, a random integer between 0 and 99 can be obtained. To transform this value into the desired range, add 1 to it.

To ensure the uniqueness of our random numbers, we implement a simple check. Using the indexOf() function, we verify that the generated number does not already exist in an array (used to store the generated numbers). If it's a new number, we add it to the array.

This process continues until the array reaches the desired number of unique random numbers.

For instance, to generate and store eight unique random numbers between 1 and 100 in an array, the following code snippet can be utilized:

var arr = [];
while (arr.length < 8) {
  var r = Math.floor(Math.random() * 100) + 1;
  if (arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
Copy after login

The above is the detailed content of How Can I Generate Unique Random Numbers Within a Specific Range in JavaScript?. 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