亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 JavaScript 中之前未選擇的數組中隨機選擇一個元素?

如何從 JavaScript 中之前未選擇的數組中隨機選擇一個元素?

jeck貓 2022-05-26 16:24:27
我想運行一個函數,每次從以前未選擇的數組中隨機選擇一個元素。如果選擇了所有元素,我想重置使用的元素并從頭開始。希望這是有道理的。我已經有一個從數組中選擇隨機元素的函數。但我也不希望它選擇之前選擇的元素,除非所有元素都已被選擇。這是我到目前為止所得到的(感謝@Kelly):var item = items[Math.floor(Math.random() * items.length)]
查看完整描述

3 回答

?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

你可以嘗試這樣的事情:

主意

  • 創建一個實用函數,它接受一個數組并返回一個隨機值。

  • 在這個 Array 里面,維護 2 個數組,choices 和 data。

  • 在每次迭代中,刪除 1 個項目data并將其放入chosenItems

  • data一旦達到長度0,設置chosenItemsoriginalArray作為數據重復處理。

這種方法的好處是,

  • 您不需要維護和傳遞數組變量。

  • 它可以通用并多次使用。

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())

}


查看完整回答
反對 回復 2022-05-26
?
慕斯709654

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

返回的項目的順序由種子排列。


查看完整回答
反對 回復 2022-05-26
?
largeQ

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>


查看完整回答
反對 回復 2022-05-26
  • 3 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號