Development/JavaScript

javascript random generate

linuxism 2012. 12. 25. 16:09


자바스크립트에서는 Math.random() 함수(메서드)로 무작위의 숫자를 출력할 수 있습니다.

그런데 Math.random()은 0~1까지의 "0.8794235627233815" 이런 실수를 반환하기에, 큰 숫자가 나오게끔 곱하기를 한 후, Math.floor() 를 사용하여 정수화시켜야 합니다.


자바스크립트: 1에서 10까지 랜덤 정수 출력 예제


<script type="text/javascript">

  var result = Math.floor(Math.random() * 10) + 1;
  document.write(result);

</script>


Math.floor(Math.random() * 100) + 1;
이렇게 하면, 1에서 100까지 나오고

Math.floor(Math.random() * 10);
이렇게 하면, 0에서 9까지 나오게 됩니다.




Math.floor() 대신 Math.round()를 사용하여 정수화하면 안됩니다. Math.round()를 사용하면 1~10까지 나오는 것이 아니라 1~11까지 나오게 됩니다.


출처 - http://mwultong.blogspot.com/2006/11/random-javascript.html