Every Time On A Button Click, Generate A UNIQUE Random Number In A Range Of 1 - 100 - JavaScript
I have a function. Every time I call the function, it should return a UNIQUE (for example, if I call this function 90 times, it should have given 90 different numbers) random numbe
Solution 1:
Make an array of a 100 numbers an cut the chosen number out each time you call it:
var unique = (function() { // wrap everything in an IIFE
var arr = []; // the array that contains the possible values
for(var i = 0; i < 100; i++) // fill it
arr.push(i);
return function() { // return the function that returns random unique numbers
if(!arr.length) // if there is no more numbers in the array
return alert("No more!"); // alert and return undefined
var rand = Math.floor(Math.random() * arr.length); // otherwise choose a random index from the array
return arr.splice(rand, 1) [0]; // cut out the number at that index and return it
};
})();
console.log(unique());
console.log(unique());
console.log(unique());
console.log(unique());
Post a Comment for "Every Time On A Button Click, Generate A UNIQUE Random Number In A Range Of 1 - 100 - JavaScript"