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 IIFEvar arr = []; // the array that contains the possible valuesfor(var i = 0; i < 100; i++) // fill it
arr.push(i);
returnfunction() { // return the function that returns random unique numbersif(!arr.length) // if there is no more numbers in the arrayreturnalert("No more!"); // alert and return undefinedvar rand = Math.floor(Math.random() * arr.length); // otherwise choose a random index from the arrayreturn 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"