Math.random()
은 0≤ x <1
의 임의의 수를 반환한다.
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:
위의 예시에서 볼 수 있듯이 모든 임의의 정수 목적에 사용할 적절한 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>