Để tạo số ngẫu nhiên, dùng Math.random(). Đặt min, max và sinh số ngẫu nhiên trong khoảng:
Ví dụ
<!DOCTYPE html>
<html>
<body>
<script>
var max = 6;
var min = 2;
// Công thức chuẩn: Math.floor(Math.random() * (max - min + 1)) + min
var random = Math.floor(Math.random() * (max - min + 1)) + min;
document.write(random);
</script>
</body>
</html>
Giải thích công thức
// Math.random() → [0, 1) (0 ≤ n < 1)
// Math.random() * (max - min + 1) → [0, max-min+1)
// Math.floor(...) → 0, 1, 2, ..., max-min
// + min → min, min+1, ..., max
// Ví dụ min=2, max=6:
// Math.random() * 5 → [0, 5)
// Math.floor → 0,1,2,3,4
// +2 → 2,3,4,5,6 ✅ (cả min và max đều có thể ra)
Hàm tiện ích reusable
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Usage
getRandomInt(1, 10); // 1-10
getRandomInt(-5, 5); // -5 đến 5
getRandomInt(100, 200); // 100-200
Lưu ý quan trọng
Math.random()trả về pseudo-random (giả ngẫu nhiên), không dùng cho cryptography.- Cần
Math.floorkhông phảiMath.round(round làm lệch phân phối ở đầu/cuối). min,maxphải là integer. DùngMath.ceil(min),Math.floor(max)để an toàn.- Crypto-secure:
crypto.getRandomValues(new Uint32Array(1))[0](Web Crypto API).