เพื่อสร้างสุ่มตัวเลข ใช้เมธอด Math.random() กำหนดค่าต่ำสุดและสูงสุด แล้วสุ่มตัวเลขระหว่างช่วงนั้น:
ตัวอย่าง
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var max = 6;
var min = 2;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
document.write(random);
</script>
</body>
</html>
สูตรมาตรฐาน
// Random integer between min (inclusive) and max (inclusive)
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// ตัวอย่าง
getRandomInt(1, 6); // 1-6 (dice)
getRandomInt(0, 100); // 0-100
getRandomInt(-5, 5); // -5 to 5
คำอธิบายสูตร
Math.random()→ คืนค่า[0, 1)(0 ถึง น้อยกว่า 1)Math.random() * (max - min + 1)→ ขยายช่วงเป็น[0, max-min+1)Math.floor(...)→ ปัดทิ้งทศนิยม ได้ integer[0, max-min]+ min→ เลื่อนช่วงเป็น[min, max]
คำเตือน
Math.random() ไม่ใช่ cryptographically secure หากต้องการความปลอดภัย ใช้ crypto.getRandomValues() (Web Crypto API)