JavaScript Tutorial.34

ansunny1170·2021년 12월 23일
0
post-thumbnail

JS RANDOM

Math.random()

Math.random()0≤ x <1 의 임의의 수를 반환한다.

JavaScript Random Integers

Math.floor()와 함께 사용되는 Math.random()은 임의의 정수를 반환하는 데 사용할 수 있다.

JavaScript 정수 같은 것은 없다.
소수점이 없는 숫자에 대해 이야기하고 있다.

  • Returns a random integer from 0 to 9:

  • Returns a random integer from 0 to 10:

  • Returns a random integer from 0 to 99:

  • Returns a random integer from 0 to 100:

  • Returns a random integer from 1 to 10:

  • Returns a random integer from 1 to 100:

A Proper Random Function

위의 예시에서 볼 수 있듯이 모든 임의의 정수 목적에 사용할 적절한 Math.random() 함수를 만드는 것이 좋다.

이 JavaScript 함수는 항상 최소(포함≤)와 최대(<제외) 사이의 임의의 수를 반환한다.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p>Every time you click the button, getRndInteger(min, max) returns a random number 
between 0 and 9 (both included):</p>
<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">
  Click Me</button>
<p id="demo"></p>
<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
</script>
</body>
</html>

이 JavaScript 함수는 항상 최소값과 최대값(둘 다 포함≤ ≤) 사이의 임의의 수를 반환한다.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p>Every time you click the button, getRndInteger(min, max) returns a random number 
between 0 and 9 (both included):</p>
<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">
Click Me</button>
<p id="demo"></p>
<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
</script>
</body>
</html>

profile
공정 설비 개발/연구원에서 웹 서비스 개발자로 경력 이전하였습니다. Node.js 백엔드 기반 풀스택 개발자를 목표로 하고 있습니다.

0개의 댓글