-
忽然笑
你可以尝试这样的事情:主意创建一个实用函数,它接受一个数组并返回一个随机值。在这个 Array 里面,维护 2 个数组,choices 和 data。在每次迭代中,删除 1 个项目data并将其放入chosenItemsdata一旦达到长度0,设置chosenItems或originalArray作为数据重复处理。这种方法的好处是,您不需要维护和传递数组变量。它可以通用并多次使用。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())}
-
慕斯709654
一种可能的方式是主要步行。首先有例如 500 个项目的列表。获取下一个大于 500 的素数。这里是 503。选择随机种子。这个种子是对用户来说是恒定的任何数字。var prime = 503;var list = ["item1", "item2", ... "item500"];function pick_nth(seed, n, p, l) { if(!n) return l[seed % p]; return pick_nth((seed + l.length) % p, n - 1, l);}从列表中提取第 n 个项目很容易。例如:pick_nth(seed, 0, prime, list); // first itempick_nth(seed, 1, prime, list); // second item...pick_nth(seed, 499, prime, list); // 500th item返回的项目的顺序由种子排列。
-
largeQ
处理此问题的最简单方法是:随机播放数组(也链接在这里)。为了简洁起见,我直接从这个答案中获取了实现并删除了评论。维护当前项目的索引。获取下一项时,获取索引并递增到下一项。完成数组后,将索引返回到开头并重新洗牌。function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array;}var items = ["alpha", "beta", "gamma", "delta", "epsilon"];var index = Infinity;function start() { console.log("----- shuffling -----") shuffle(items); index = 0;}function nextItem() { if (index >= items.length) { //re-start start() } //return current index and increment return items[index++];}document.getElementById("click_me") .addEventListener("click", function() { console.log(nextItem()) })<button id="click_me">Next random</button>这也可以转换为生成器函数function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array;}function* random(array) { let index = Infinity; const items = array.slice(); //take a copy of the array; while(true) { if (index >= array.length) { console.log("----- shuffling -----") shuffle(items); index = 0; } yield items[index++]; }}var items = ["alpha", "beta", "gamma", "delta", "epsilon"];//start the generatorconst generateRandom = random(items);document.getElementById("click_me") .addEventListener("click", function() { console.log(generateRandom.next().value) })<button id="click_me">Next random</button>