Math.random 메서드
Math.random 메서드는 0부터 1까지의
임의의 부동 소수점 숫자를 반환합니다.
구문
Math.random();
사용법
특정 범위(정수 또는 부동 소수점)의 난수를 얻으려면
특별한 기법을 사용해야 합니다.
min과 max 사이의 임의의 부동 소수점 숫자를
얻는 방법은 다음과 같습니다:
function getRandomArbitary(min, max) {
return Math.random() * (max - min) + min;
}
이제 min과 max 사이의 임의의 정수를 얻어보겠습니다:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
예제
0부터 1까지의 난수를 출력해 봅시다:
console.log(Math.random());
코드 실행 결과:
0.5416665468657356
예제
10부터 100까지의 임의의 정수를 출력해 봅시다:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(10, 100));
코드 실행 결과:
12