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