从集合中生成随机数,以便使用javascript拾取每个数字
我有一个数组arr[8,4,2,1,7,5,3,0],它有8个元素。我想从数组中随机选取每个数字,这样每个数字都会被选取,没有一个会重复。我希望每个号码只选一次 你的意思是这样的从集合中生成随机数,以便使用javascript拾取每个数字,javascript,Javascript,我有一个数组arr[8,4,2,1,7,5,3,0],它有8个元素。我想从数组中随机选取每个数字,这样每个数字都会被选取,没有一个会重复。我希望每个号码只选一次 你的意思是这样的 函数getRandomInt(最大值){ 返回Math.floor(Math.random()*Math.floor(max)); } 设arr=[8,4,2,1,7,5,3,0], selectedIndex=[]; 函数getRandomValue(){ 让randomIndex=Math.floor(Math.
函数getRandomInt(最大值){
返回Math.floor(Math.random()*Math.floor(max));
}
设arr=[8,4,2,1,7,5,3,0],
selectedIndex=[];
函数getRandomValue(){
让randomIndex=Math.floor(Math.random()*Math.floor(arr.length));
如果(已选择索引索引OF(随机索引)!=-1){
返回getRandomValue()
}
选择索引推送(随机索引);
返回arr[随机索引]
}
arr.forEach(()=>{
log(getRandomValue());
})一种可能的方法是
let number=[8,4,2,1,7,5,3,0];
让洗牌=(o)=>{
对于(var j,x,i=o.length;i;j=parseInt(Math.random()*i),x=o[--i],o[i]=o[j],o[j]=x);
返回o;
};
log(shuffle(numbers))
我会简化这个过程,只需要一个基本的,而循环:
const array=[8,4,2,1,7,5,3,0];
while(array.length>0) {
let i = Math.floor(Math.random() * Math.floor(array.length));
console.log(`Picked this number: ${array[i]}`);
array.splice(i,1);
};
样本输出:
// "Picked this number: 5"
// "Picked this number: 1"
// "Picked this number: 0"
// "Picked this number: 7"
// "Picked this number: 8"
// "Picked this number: 2"
// "Picked this number: 3"
// "Picked this number: 4"
代码笔:
所有这些都是计算数组中的元素数,随机选取一个元素,将其吐出,然后将其从数组中移除。它执行(,而
)数组包含元素。一旦将它们全部取出,它将停止运行。欢迎使用StackOverflow!到目前为止你试过什么吗?请更新您的问题,以显示您已经尝试过的内容,并显示您在某个应用程序中面临的特定问题。欲了解更多信息,请参阅,然后点击。