Math.random()

조아영·2024년 6월 28일

📌

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

0개의 댓글