เพื่อสุ่มตัวเลขระหว่างสองตัวเลข ให้ใช้เมธอด Math.random()
ตัวอย่าง
คุณสามารถลองรันโค้ดต่อไปนี้เพื่อได้ตัวเลขสุ่มระหว่างค่าต่ำสุดและสูงสุด:
Live Demo
<!DOCTYPE html> <html> <body> <script> function randomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } alert(randomInt(5,25)); </script> </body> </html>