从数组中随机选择没有重复

时间:2016-01-21 00:57:18

标签: jquery

我需要从数组中选择一个元素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 个答案:

答案 0 :(得分: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数组的深层克隆并拼接元素。