티스토리 뷰

Math.random

0 ~ 1 사이의 랜덤한 숫자를 반환합니다.

단, 1은 포함되지 않는 부동소수점의 수를 발생 시키기 때문에 정수형 데이터로 변환해야 합니다.

Math.random();

// 함수 실행 시, 아래와 같은 결과값 반환
0.787910016396766
0.9811818120683229
0.018731720450270606
0.26159482631296616
0.4618645356440654
0.5720506552882538
0.8146460036266621

 

 

Math.floor

입력값을 내림한 가장 작은 정수값을 반환 합니다.

Math.floor(-1.7) : -2
Math.floor(-1.5) : -2
Math.floor(-1.3) : -2
Math.floor(-1) : -1
Math.floor(null) : 0
Math.floor(0) : 0
Math.floor(1.0) : 1
Math.floor(1.3) : 1
Math.floor(1.5) : 1
Math.floor(1.7) : 1

 

 

Math.floor + Math.random

Math.floor() 함수와 Math.random() 함수를 이용하여, 원하는 구간별 난수를 발생시킬 수 있습니다.

// 0 ~ 5
Math.floor(Math.random() * 6)
0
2
5

// 0 ~ 9
Math.floor(Math.random() * 10)
0
2
9

// 0 ~ 10
Math.floor(Math.random() * 11)
0
2
10

// 0 ~ 99
Math.floor(Math.random() * 100)
97
84
73

// 0 ~ 100
Math.floor(Math.random() * 101)
15
48
100
댓글