3 回答

TA貢獻1806條經驗 獲得超5個贊
你可以嘗試這樣的事情:
主意
創建一個實用函數,它接受一個數組并返回一個隨機值。
在這個 Array 里面,維護 2 個數組,choices 和 data。
在每次迭代中,刪除 1 個項目
data
并將其放入chosenItems
data
一旦達到長度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())
}

TA貢獻1840條經驗 獲得超5個贊
一種可能的方式是主要步行。
首先有例如 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 item
pick_nth(seed, 1, prime, list); // second item
...
pick_nth(seed, 499, prime, list); // 500th item
返回的項目的順序由種子排列。

TA貢獻2039條經驗 獲得超8個贊
處理此問題的最簡單方法是:
隨機播放數組(也鏈接在這里)。為了簡潔起見,我直接從這個答案中獲取了實現并刪除了評論。
維護當前項目的索引。
獲取下一項時,獲取索引并遞增到下一項。
完成數組后,將索引返回到開頭并重新洗牌。
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 generator
const generateRandom = random(items);
document.getElementById("click_me")
.addEventListener("click", function() {
console.log(generateRandom.next().value)
})
<button id="click_me">Next random</button>
添加回答
舉報