[JavaScript] 랜덤 숫자 생성하기 (Math.random())

Math.random()

0이상 1이하의 난수를 생성하는 함수.

Math.random이 생성하는 난수는 안전한 값이 아니므로 보안에 신경써야 할 때에는 window.crypto.getRandomValues() 를 이용해야 한다고 한다.

 

두 수 사이의 값을 리턴받고싶을 땐 아래 공식을 활용할 수 있다.

+1을 하는 이유는 최댓값을 포함시키기 위함이고, min을 하는 이유는 최솟값을 포함하기 위함이다.

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

 

두 수 사이의 정수를 리턴받고싶을 땐 내림 함수인 Math.floor로 감싸 해결할 수 있다.

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

 

 

 

참고자료 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/random