ในการสร้างตัวเลขสุ่มระหว่างสองตัวเลข ใช้วิธี Math.random()
ตัวอย่าง
คุณสามารถลองเรียกใช้รหัสต่อไปนี้เพื่อรับตัวเลขสุ่มระหว่างจำนวนต่ำสุดและสูงสุด -
การสาธิตสด
<!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>