如何从JavaScript中以前未选择的数组中随机选择一个元素? [英] How to Randomly Choose an Element from an Array that Wasn't Chosen before in JavaScript?

查看:24
本文介绍了如何从JavaScript中以前未选择的数组中随机选择一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个函数,每次随机从以前未选择的数组中随机选择一个元素.如果所有元素都被选中,我想重置使用过的元素并从头开始.

I want to run a function that each time randomly chooses an element from an array that wasn't chosen before. And if all elements were chosen, I want to reset the used elements and start from the beginning.

希望这是有道理的.

我已经有了一个从数组中选择随机元素的函数.但是我也不希望它选择以前选择的元素,除非所有元素都已被选择.

I already have a function that chooses a random element from an array. But I also don't want it to choose elements that were chosen before unless all elements were already chosen.

这是我到目前为止所获得的(贷记@Kelly):

Here is what I have got so far (credit to @Kelly):

var item = items[Math.floor(Math.random() * items.length)]

推荐答案

您可以尝试执行以下操作:

You can try something like this:

  • 创建一个实用函数,该函数接受一个数组并返回一个随机值.
  • 在此数组内,维护2个数组,选择和数据.
  • 在每次迭代中,从 data 中删除一项,并将其放入 chosenItems
  • 一旦 data 的长度达到 0 ,将 chosenItems originalArray 设置为数据并重复处理./li>
  • Create a utility function that takes an array and returns you a random value.
  • Inside this Array, maintain 2 array, choices and data.
  • In every iteration, remove 1 item from data and put it in chosenItems
  • Once the length of data reaches 0, set chosenItems or originalArray as data and repeat process.

这种方法的好处是,

  • 您不需要维护和传递数组变量.
  • 可以使其通用并多次使用.

function randomize(arr) {
  let data = [...arr];
  let chosenItems = [];

  function getRandomValue() {
    if (data.length === 0) {
      data = chosenItems;
      chosenItems = [];
    }
    const index = Math.floor(Math.random() * data.length);
    const choice = data.splice(index, 1)[0];

    chosenItems.push(choice);
    return choice;
  }
  
  return {
    randomItem: getRandomValue
  }
}

const dummyData = [ 1,2,3,4,5 ];

const randomizeData = randomize(dummyData);

for (let i = 0; i< 10; i++) {
  console.log(randomizeData.randomItem())
}

这篇关于如何从JavaScript中以前未选择的数组中随机选择一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆