每次单击按钮,都会生成一个唯一的随机数,范围为1-100-JavaScript [英] Every Time on a button click, generate a UNIQUE random number in a range of 1 - 100 - JavaScript
本文介绍了每次单击按钮,都会生成一个唯一的随机数,范围为1-100-JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个功能.每次调用该函数时,它都应返回一个唯一值(小于100的随机数)(例如,如果我调用此函数90次,则应给出90个不同的数字).
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 number under 100.
我正在做
var randomNumber = Math.floor(Math.random() * 100);
但是,它没有返回唯一的数字.它只是返回随机数.
But, it's not returning unique numbers. It's only returning random numbers.
谢谢.
修改:呼叫100次后,它应该返回一些警报.
It should return some alert after calling 100 times.
推荐答案
使100个数字组成的数组会在每次您调用它时将选定的数字切掉:
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());
这篇关于每次单击按钮,都会生成一个唯一的随机数,范围为1-100-JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文