簡體   English   中英

如果javascript中的值相同,如何再次使用math.random獲得不同的值

[英]How to use math.random again to get a different value if the values are the same in javascript

我試圖從以前的math.random值中獲得一個不同的值,所以當數字寫入文檔時,如果它們相同,則math.random將生成另一個不同的數字。 它可能需要繼續生成,直到值不同為止。

function rands() {
  return Math.floor(Math.random() * 20) + 1;
}

var rand1 = rands();
var rand2 = rands();
var rand3 = rands();
var rand4 = rands();
var rand = [];

function myFunction() {
  document.getElementById("random1").value = rand1;
  document.getElementById("random2").value = rand2;
  document.getElementById("random3").value = rand3;
  document.getElementById("random4").value = rand4;

  if(rand1 == rand2 || rand1==rand3 || rand1==rand4 || rand2 == rand3 || rand2 == rand4 || rand3==rand4){
  console.log("Duplicate");

    }
}

myFunction()

您可以重寫rands函數以查找已使用的值:

function rands(used) {
    let r;
    do {
        r = Math.floor(Math.random() * 20) + 1;
    } while (used.indexOf(r) >= 0);
    return r;
}

var rand = [];
for (let i = 0; i < 4; i++) rand[i] = rands(rand);

如果要保證唯一性,可以從數組中拼接隨機索引。 這樣可以避免發生沖突時重復調用該函數的工作:

 function rand_maker(length) { let arr = Array.from({length: length}, (_, i) => i+1) return () => { let index = Math.floor(Math.random() * arr.length) return arr.splice(index, 1)[0]; } } let rands = rand_maker(20) console.log(rands()) console.log(rands()) console.log(rands()) console.log(rands()) 

一旦無法再在該范圍內生成隨機數,它將返回未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM