728x90

✨ 무작위(random)숫자를 얻기 위한 helper method

💻Example Code

const randomNum = Math.random();
const max = 3;

console.log( randomNum ); // 0 ~ 0.99999...
console.log( randomNum * max ); // 0 ~ 2.9999.....

위 코드를 3번 실행한 결과

기본적으로, Math.random()은 0 ~ 0.999...까지 값을 얻을 수 있다(1은 포함되지 않는다)
하지만, 위 코드처럼 max값을 곱해주면 0 ~ 2.999...까지 값을 얻을 수 있다(3은 포함되지 않는다)
이렇게 범위를 정해서 내가 원하는 random 값을 받아볼 수 있다.

📌 만약 1부터 3까지 값을 받고 싶다면?

Math.ceil( Math.random * 최대 범위 )
위와 같이 ceil(올림) method를 사용해주면 된다(여러가지 다른 방법도 있다)

console.log( Math.ceil(Math.random() * 3) );

위 코드를 3번 실행한 결과

📌 function을 사용하여 간편하게 이용하는 방법도 있다.

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

const max = 3;

console.log( getRandomInt(max) );

위 코드를 3번 실행한 결과

위 function에서는 Math.floor( Math.random() * max ) + 1; 로 작성했다.
즉, 0 ~ 2.999...범위의 random 숫자를 버림(floor)해주고 +1을 더해 주는 방식이다.
이렇게 작성해도 1~3까지 범위의 random 숫자를 받아볼 수 있다.

😋 기본적으로 구구단 게임이라든지, 무언가 변칙적인 개발이 필요할 때 자주 사용되는 method!
종종 쓰이기 때문에, 한 번 잘 이해해두고 앞으로 쉽게 사용하자.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

 

Math.random()

The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.forEach()  (0) 2020.01.23
Math.pow()  (0) 2020.01.22
Math.ceil()  (0) 2020.01.18
Array.prototype.filter()  (0) 2020.01.11
Array.prototype.map()  (0) 2020.01.11

+ Recent posts