簡體   English   中英

JavaScript:Math.random() 返回相同的數字。 我該如何阻止這個?

[英]JavaScript: Math.random() returning the same numbers. How do I stop this?

我有一個 JavaScript 字符串數組,我想從數組中選擇一個隨機字符串。 但是,當它在 Edge 和 Chrome 中運行時,它不會拋出任何錯誤,而是每次都從數組中選擇相同的字符串。 我查看了 Stack Overflow 上的其他答案,但似乎都沒有幫助。 這是我的代碼:

 var arr = ["string1", "string2", "string3", "string4", "string5", "string6", "string7"]; /* 100 quotes in the real array. */ var dis = parseInt(prompt("Enter the number of strings you would like to display.")); if(dis > arr.length) { alert("You have entered a number that is too great."); } else { for(var n = 1; n <= dis; n++) { document.write(arr[(Math.random() * (arr.length - 1))] + "<br/>"); } }

任何人都有任何代碼片段可以確保它不會選擇相同的字符串?

也許是因為您需要將 Math.random 轉換為 integer。 嘗試這個。

document.write(arr[parseInt((Math.random()*(arr.length-1)))]+"<br/>");

你可以試試:

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

//////////////

document.write(arr[getRandomInt(0, arr.length-1)]+"<br/>");

通過使用Math.floor()向下舍入,使用 int 作為索引。

 var arr = ["string1", "string2", "string3", "string4", "string5", "string6", "string7"]; /* 100 quotes in the real array. */ var dis = parseInt(prompt("Enter the number of strings you would like to display.")); if(dis > arr.length) { alert("You have entered a number that is too great."); } else { for(var n = 1; n <= dis; n++) { document.write(arr[Math.floor(Math.random() * arr.length)] + "<br/>"); } }

暫無
暫無

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

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