Math.random() 回傳 [0, 1) 的偽隨機浮點數。本文整理常見的隨機整數、指定範圍隨機數公式,並補充以時間為種子的替代方案。
Math.random()Math.random() * (n - m) + mMath.floor(Math.random() * (max - min + 1)) + min// 10 到 20 之間的隨機數(含小數)
Math.random() * (20 - 10) + 10;
// 10 到 20 之間的隨機整數
Math.floor(Math.random() * 11) + 10;
var now = new Date();
var rnd = now.getSeconds(); // 0-59
var rnd43 = now.getSeconds() % 43; // 0-42
此法簡單但隨機性較差,僅適合簡單展示或非關鍵邏輯。需加密級隨機請使用 crypto.getRandomValues()。