取得隨機數是 JavaScript 的基礎技能,但 Math.random() 的行為常常不符合期待。本文從最基礎的行為談起,逐步推導出一個通用的區間隨機函式。
它回傳一個大於等於 0 且小於 1 的浮點數。注意是「小於 1」,所以永遠不會剛好等於 1。
寫 Math.random() * 10,得到的是 0 到 10 之間的小數,但取不到 10。要讓範圍變成 1 到 10,在後面加 1 即可:
Math.random() * 10 + 1
不過這時結果還是小數,並不符合要求。這裡就需要 Math.floor()——它執行向下取整,所以 10.99 會變成 10。
相對地,Math.ceil() 是向上取整,即使是 10.00001 也會回傳 11。做隨機整數時通常不該用它,因為它會讓最小值出現的機率只有其他數的一半。
結果就出來了:
Math.floor(Math.random() * 10 + 1); // 1 到 10 的隨機整數
Math.floor(Math.random() * 9 + 2);
3 到 11、4 到 88……如果每次都這樣手算範圍寬度,實在麻煩。與其如此,不如寫成通用函式。
function selectFrom(lowValue, highValue) {
var choice = highValue - lowValue + 1;
return Math.floor(Math.random() * choice + lowValue);
}
關鍵那個 + 1 千萬不能少。因為 Math.random() 取不到 1,若不補上 1,區間的最大值永遠不會出現——例如 Math.floor(Math.random() * 10) 只能產生 0 到 9。
之後直接呼叫即可:
selectFrom(1, 10); // 1 到 10 selectFrom(4, 88); // 4 到 88
第一,若要取隨機浮點數而非整數,就不該用 floor,直接回傳 lowValue + Math.random() * (highValue - lowValue) 即可。
第二,Math.random() 是偽隨機數,由演算法產生,)不適合用於密碼、權杖等安全相關場景。這類需求請改用 crypto.getRandomValues() 或 Node.js 的 crypto.randomInt()。
第三,若要加權隨機(例如讓某些選項出現機率較高),可以在上述函式基礎上再包一層權重表,不必重新設計隨機邏輯。