jennet1 님의 블로그

JS [random] 본문

WEB/JS

JS [random]

jennet1 2024. 9. 23. 15:39

1. rand 함수란?

- 임의의 정수를 반환하는 함수, 주어진 범위 내에서 무작위 값을 생성한다.

Math.random() 함수 : 0 과 1 사이의 소수 값을 반환한다.

let randomValue = Math.random();
console.log(randomValue); // 예: 0.123456789

정수로 출력하기 위해 추가적인 작업이 필요하다

 

1~10 사이의 정수 생성

let randomValue = Math.floor(Math.random() * 10) + 1;
console.log(randomValue); // 1부터 10까지의 정수 출력

Math.floor() : 소수점 아래를 버리고 Math.random() * 10은 0부터 9.9999..까지의 값을 반환해서

1부터 10까지의 랜덤값을 얻을 수 있다.

 

범위를 설정하는 함수를 만들어보자

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomInt(5, 15)); // 5부터 15까지의 정수 출력

 

예제 : 랜덤 숫자 추첨기

See the Pen Untitled by 성은총 (@xxlblqtl-the-selector) on CodePen.

'WEB > JS' 카테고리의 다른 글

JS [Value 속성]  (0) 2024.09.23
JS [이벤트 발생]  (1) 2024.09.23
JS [children childrenNodes]  (0) 2024.09.22
JS [DOM TEXT]  (0) 2024.09.21
JS [DOM]  (0) 2024.09.21