猿问

如何从 JavaScript 中之前未选择的数组中随机选择一个元素?

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

希望这是有道理的。

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

这是我到目前为止所得到的(感谢@Kelly):

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


jeck猫
浏览 162回答 3
3回答

忽然笑

你可以尝试这样的事情:主意创建一个实用函数,它接受一个数组并返回一个随机值。在这个 Array 里面,维护 2 个数组,choices 和 data。在每次迭代中,删除 1 个项目data并将其放入chosenItemsdata一旦达到长度0,设置chosenItems或originalArray作为数据重复处理。这种方法的好处是,您不需要维护和传递数组变量。它可以通用并多次使用。function randomize(arr) {&nbsp; let data = [...arr];&nbsp; let chosenItems = [];&nbsp; function getRandomValue() {&nbsp; &nbsp; if (data.length === 0) {&nbsp; &nbsp; &nbsp; data = chosenItems;&nbsp; &nbsp; &nbsp; chosenItems = [];&nbsp; &nbsp; }&nbsp; &nbsp; const index = Math.floor(Math.random() * data.length);&nbsp; &nbsp; const choice = data.splice(index, 1)[0];&nbsp; &nbsp; chosenItems.push(choice);&nbsp; &nbsp; return choice;&nbsp; }&nbsp;&nbsp;&nbsp; return {&nbsp; &nbsp; randomItem: getRandomValue&nbsp; }}const dummyData = [ 1,2,3,4,5 ];const randomizeData = randomize(dummyData);for (let i = 0; i< 10; i++) {&nbsp; console.log(randomizeData.randomItem())}

慕斯709654

一种可能的方式是主要步行。首先有例如 500 个项目的列表。获取下一个大于 500 的素数。这里是 503。选择随机种子。这个种子是对用户来说是恒定的任何数字。var prime = 503;var list = ["item1", "item2", ... "item500"];function pick_nth(seed, n, p, l) {&nbsp; &nbsp; if(!n) return l[seed % p];&nbsp; &nbsp; return pick_nth((seed + l.length) % p, n - 1, l);}从列表中提取第 n 个项目很容易。例如:pick_nth(seed, 0, prime, list);&nbsp; // first itempick_nth(seed, 1, prime, list);&nbsp; // second item...pick_nth(seed, 499, prime, list);&nbsp; // 500th item返回的项目的顺序由种子排列。

largeQ

处理此问题的最简单方法是:随机播放数组(也链接在这里)。为了简洁起见,我直接从这个答案中获取了实现并删除了评论。维护当前项目的索引。获取下一项时,获取索引并递增到下一项。完成数组后,将索引返回到开头并重新洗牌。function shuffle(array) {&nbsp; var currentIndex = array.length, temporaryValue, randomIndex;&nbsp; while (0 !== currentIndex) {&nbsp; &nbsp; randomIndex = Math.floor(Math.random() * currentIndex);&nbsp; &nbsp; currentIndex -= 1;&nbsp; &nbsp; temporaryValue = array[currentIndex];&nbsp; &nbsp; array[currentIndex] = array[randomIndex];&nbsp; &nbsp; array[randomIndex] = temporaryValue;&nbsp; }&nbsp; return array;}var items = ["alpha", "beta", "gamma", "delta", "epsilon"];var index = Infinity;function start() {&nbsp; console.log("----- shuffling -----")&nbsp; shuffle(items);&nbsp; index = 0;}function nextItem() {&nbsp; if (index >= items.length) {&nbsp; &nbsp; //re-start&nbsp; &nbsp; start()&nbsp; }&nbsp;&nbsp;&nbsp; //return current index and increment&nbsp; return items[index++];}document.getElementById("click_me")&nbsp; .addEventListener("click", function() {&nbsp; &nbsp; console.log(nextItem())&nbsp; })<button id="click_me">Next random</button>这也可以转换为生成器函数function shuffle(array) {&nbsp; var currentIndex = array.length, temporaryValue, randomIndex;&nbsp; while (0 !== currentIndex) {&nbsp; &nbsp; randomIndex = Math.floor(Math.random() * currentIndex);&nbsp; &nbsp; currentIndex -= 1;&nbsp; &nbsp; temporaryValue = array[currentIndex];&nbsp; &nbsp; array[currentIndex] = array[randomIndex];&nbsp; &nbsp; array[randomIndex] = temporaryValue;&nbsp; }&nbsp; return array;}function* random(array) {&nbsp; let index = Infinity;&nbsp; const items = array.slice(); //take a copy of the array;&nbsp;&nbsp;&nbsp; while(true) {&nbsp; &nbsp; if (index >= array.length) {&nbsp; &nbsp; &nbsp; console.log("----- shuffling -----")&nbsp; &nbsp; &nbsp; shuffle(items);&nbsp; &nbsp; &nbsp; index = 0;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; yield items[index++];&nbsp; }}var items = ["alpha", "beta", "gamma", "delta", "epsilon"];//start the generatorconst generateRandom = random(items);document.getElementById("click_me")&nbsp; .addEventListener("click", function() {&nbsp; &nbsp; console.log(generateRandom.next().value)&nbsp; })<button id="click_me">Next random</button>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答