Home >Web Front-end >JS Tutorial >How to Generate Unique Random Numbers Between 1 and 100 in JavaScript?

How to Generate Unique Random Numbers Between 1 and 100 in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 13:57:10305browse

How to Generate Unique Random Numbers Between 1 and 100 in JavaScript?

Generating Unique Random Numbers Between 1 and 100 in JavaScript

Generating truly random numbers can be a challenging task in any programming language. However, JavaScript provides us with a simple way to generate a sequence of pseudo-random numbers using the Math.random() function. While these numbers may not be completely unpredictable, they can be used to create the illusion of randomness for many purposes.

One common problem that arises when using Math.random() is the possibility of generating duplicate values, especially when dealing with a有限的范围 like 1 to 100. To overcome this issue, we can employ a simple strategy to ensure that each randomly generated number is unique.

Solution:

while(array.length < n) {} The while loop continues to add unique numbers to the array arr until a total of n (e.g., 8) unique numbers have been generated.

random = Math.floor(Math.random() * 100) 1 This line generates a random number between 1 and 100 (inclusive).
array.indexOf(random) === -1 This condition checks if the generated random number already exists in the array. If not, it means the number is unique, so we add it to the array using array.push(random).

Example:

The code snippet provided in the answer illustrates how to generate eight unique random numbers within the range of 1 to 100 and store them in an array called arr. You can modify the value of n to specify the desired number of unique random numbers to be generated.

The above is the detailed content of How to Generate Unique Random Numbers Between 1 and 100 in JavaScript?. 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