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

How to Generate Unique Random Numbers in JavaScript?

Linda Hamilton
Release: 2024-12-14 00:49:10
Original
626 people have browsed it

How to Generate Unique Random Numbers in JavaScript?

Generating Unique Random Numbers in JavaScript

When working with data in JavaScript, it's often necessary to generate random numbers for various purposes. However, in some cases, we may need to ensure that the random numbers generated are unique within a specified range. This can be achieved using a combination of built-in JavaScript functions and logical checks.

Question:

How can we generate unique random numbers between 1 and 100 using JavaScript?

Answer:

To generate unique random numbers, we can follow these steps:

  1. Initialize an empty array: Declare an array to store the unique random numbers.
  2. Generate a random number: Use the Math.random() function to generate a random number between 0 and 0.999999.
  3. Scale the number: Multiply the random number by 100 to get a random integer between 0 and 99.
  4. Add 1: Add 1 to the random integer to get a number between 1 and 100.
  5. Check for uniqueness: Check if the generated number already exists in the array using the indexOf() method.
  6. If unique: If the number is not found in the array, push it into the array.
  7. Repeat: Repeat steps 2-6 until the desired number of unique random numbers is generated.

Example Implementation:

To generate and store 8 unique random numbers in an array, you can use the following JavaScript code:

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

This code will output an array of 8 unique random numbers between 1 and 100.

The above is the detailed content of How to Generate Unique Random Numbers 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