2016-01-21 53 views
0

我需要从阵列选择一个元件10周不同的时间,而不在该过程中挑选任何重复:随机挑选,而不重复

function raffle(){ 
    question_pool = Array(a,b,c,d,e,f,g,h,i,j,k,l,m); 
    question = question_pool[Math.floor(Math.random()*question_pool.length)]; 
} 

这是我的函数raflle()中,当我执行它,我可能会得到两次结果。

这里是方法:

question_pool = Array(a,b,c,d,e,f,g,h,i,j,k,l,m); 
maximum = 10; 
minimum = 0; 
question_stack = Math.floor(Math.random() * question_pool.length - minimum); 
minimum = Math.min(minimum + 1, maximum); 
question = question_pool.splice(question_stack,1); 
question_pool.push(question); 
+1

不要将它推回到阵列中。一旦你删除它,你不能再选择 – charlietfl

回答

0

使用剪接删除从问题池中选择的问题。一旦所有问题都已绘制完毕,请继续。

var question_pool = Array("a","b","c","d","e","f","g","h","i","j","k","l","m"); 
do{ 
    var id = Math.floor(Math.random() * question_pool.length);; 
    var question = question_pool[id]; 
    question_pool.splice(id, 1); 
    console.log(question); 
}while(question_pool.length > 0); 

https://jsfiddle.net/nc67chwn/

随后,您可以创建question_pool阵列和拼接元素的深克隆的,如果你想保留原始问题分组。

+0

谢谢! PERFEKT。似乎是合法的! – fabuchao