问题描述
基本上我选择0-24之间的随机数:
Basically I pick a random number between 0-24:
Math.floor(Math.random() * myArray.length); // myArray contains 25 items
假设结果是 8.现在我想得到另一个在 0-24 范围内的数字,但这次,我不想要 8.下一次,我可能会掷出 15.现在我想要再次滚动,但我不想要 8 或 15.我现在处理此问题的方式是使用 do while 循环,如果数字相同,我只需重新滚动.
Lets say it comes out to be 8. Now I want to get another number in the same range 0-24 but this time, I do not want an 8. The next time, I might roll a 15. Now I want to roll again but I don't want an 8 or 15. The way I am handling this now is by using do while loops and if the number comes out the same, I just reroll.
这是我家庭作业的一小部分,事实上,我已经让它满足所有要求,所以我想你可以说这是为了我个人的利益,所以我可以正确地写这个而不是结束每日wtf".
This is a small portion of my homework and I, in fact, have it working to meet all the requirements so I guess you could say this is for my own personal benefit so I can write this properly and not end up on "the daily wtf".
推荐答案
设置一个包含所有值的数组(如果你只做小数字,这只是一个有效的选项,比如你的例子中的 25),像这样:
Set an array with all the values (this is only a valid option if you're only doing small numbers, like the 25 in your example), like this:
var array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
然后,在 0 和数组长度之间选择一个随机数:
then, pick a random number between 0 and the array length:
var num = Math.floor(Math.random() * array.length);
从数组中删除该索引号:
var roll = array.splice(num, 1);
Javascript splice()从数组中删除索引项并将项作为数组返回.非常适合您使用.
Javascript splice() removes indexed items from an array and returns the item(s) as an array. Perfect for your use.
从卷中获取第一个索引,因为无论如何我们只删除了 1 个:
Grab the first index from the roll, since we only cut 1 out anyway:
var yourNumber = roll[ 0 ];
继续做尽可能多的卷.此外,您可能希望将原始数组存储为副本,以便轻松重置"数字.
Keep doing for as many rolls as you want. Also, you might want to store the original array as a copy so that you can "reset" the numbers easily.
这篇关于如何生成一个范围内的随机数但排除一些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!