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:
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);
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!