Math.random()은 0 이상과 1 미만의 수를 무작위로 생성하는 함수입니다.
function getRandom() {
return Math.random(); // 0.7247167230943277
}
정수인 난수를 생성하려면 Math.random()와 Math.floor()를 함께 사용해야합니다.
Math.floor() : 지정된 수보다 작거나 같은 최대 정수 값을 반환합니다.
Math.ceil() : 지정된 수보다 크거나 같은 최소 정수 값을 반환합니다.
function getRandomInt(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
// 최댓값은 제외, 최솟값은 포함
return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled);
}
function getRandomIntInclusive(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
// 최댓값도 포함, 최솟값도 포함
return Math.floor(Math.random() * (maxFloored - minCeiled + 1) + minCeiled);
}
※ 참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/random