似乎无法找到答案,说我有这个:
Can't seem to find an answer to this, say I have this:
setInterval(function() { m = Math.floor(Math.random()*7); $('.foo:nth-of-type('+m+')').fadeIn(300); }, 300);如何使随机数不重复。例如,如果随机数是2,我不希望2再出来。
How do I make it so that random number doesn't repeat itself. For example if the random number is 2, I don't want 2 to come out again.
推荐答案有一些你可以实现这个目标。
There are a number of ways you could achieve this.
解决方案A:如果数字范围不大(假设小于10),你可以跟踪你已经生成的数字。然后,如果你生成一个副本,丢弃它并生成另一个数字。
Solution A: If the range of numbers isn't large (let's say less than 10), you could just keep track of the numbers you've already generated. Then if you generate a duplicate, discard it and generate another number.
解决方案B:预先生成随机数,将它们存储到数组中然后通过阵列。您可以通过取数字 1,2,...,n 然后随机播放来完成此操作。
Solution B: Pre-generate the random numbers, store them into an array and then go through the array. You could accomplish this by taking the numbers 1,2,...,n and then shuffle them.
shuffle = function(o) { for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }; var randorder = shuffle([0,1,2,3,4,5,6]); var index = 0; setInterval(function() { $('.foo:nth-of-type('+(randorder[index++])+')').fadeIn(300); }, 300);解决方案C:跟踪数组中可用的数字。随机挑一个号码。从所述数组中删除数字。
Solution C: Keep track of the numbers available in an array. Randomly pick a number. Remove number from said array.
var randnums = [0,1,2,3,4,5,6]; setInterval(function() { var m = Math.floor(Math.random()*randnums.length); $('.foo:nth-of-type('+(randnums[m])+')').fadeIn(300); randnums = randnums.splice(m,1); }, 300);更多推荐
数学随机数,不重复前一个数字
发布评论