ใช้ Math.random() ร่วมกับ Math.floor() เพื่อสุ่มจำนวนเต็มในช่วงที่ต้องการ
สูตรทั่วไป
Math.floor(Math.random() * (max + 1))
สำหรับช่วง 0 ถึง 199 ใช้ Math.floor(Math.random() * 200)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Math.floor(Math.random() * 200));
</script>
</body>
</html>
การทำงาน
Math.random()สุ่มทศนิยม 0 ≤ x < 1- คูณ 200 → ช่วง 0 ≤ x < 200
Math.floor()ปัดทิ้งทศนิยม → จำนวนเต็ม 0 ถึง 199
ฟังก์ชันสำเร็จรูป (Reusable)
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
// ใช้งาน: getRandomInt(200) // 0-199
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// ใช้งาน: getRandomIntInclusive(0, 199)
หมายเหตุ: Math.random() ไม่เหมาะสำหรับ Cryptography ใช้ crypto.getRandomValues() แทน