반응형
JavaScript의 Math
객체는 수학적인 계산을 수행하는 데 사용되며, 다양한 메서드와 상수를 제공한다.Math
객체는 정적(static) 객체이므로, new Math()
로 인스턴스를 생성하지 않고 바로 사용 가능하다.
1. Math
객체의 주요 메서드
메서드 | 설명 | 예제 |
---|---|---|
Math.abs(x) |
절댓값 반환 | Math.abs(-10) // 10 |
Math.ceil(x) |
올림 (소수점 올림) | Math.ceil(4.3) // 5 |
Math.floor(x) |
내림 (소수점 버림) | Math.floor(4.9) // 4 |
Math.round(x) |
반올림 | Math.round(4.4) // 4 , Math.round(4.6) // 5 |
Math.trunc(x) |
소수점 이하 제거 (버림) | Math.trunc(4.9) // 4 |
Math.sqrt(x) |
제곱근 반환 | Math.sqrt(25) // 5 |
Math.pow(x, y) |
거듭제곱 (x^y ) |
Math.pow(2, 3) // 8 |
Math.max(x, y, …) |
최댓값 반환 | Math.max(10, 5, 20) // 20 |
Math.min(x, y, …) |
최솟값 반환 | Math.min(10, 5, 20) // 5 |
Math.random() |
0 이상 1 미만의 난수 생성 | Math.random() // 0.34567 |
Math.sign(x) |
양수(1), 음수(-1), 0(0) 판별 | Math.sign(-5) // -1 |
Math.log(x) |
자연로그(ln x) 계산 | Math.log(10) |
Math.exp(x) |
e^x 값 반환 | Math.exp(2) |
Math.sin(x) |
사인 함수 (x 는 라디안 단위) |
Math.sin(Math.PI / 2) // 1 |
Math.cos(x) |
코사인 함수 | Math.cos(0) // 1 |
Math.tan(x) |
탄젠트 함수 | Math.tan(Math.PI / 4) // 1 |
2. Math
객체의 주요 상수
상수 | 설명 | 값 |
---|---|---|
Math.PI |
원주율(π) | 3.141592653589793 |
Math.E |
자연로그의 밑 (e) | 2.718281828459045 |
Math.LN2 |
log(2) (자연로그) |
0.6931471805599453 |
Math.LN10 |
log(10) (자연로그) |
2.302585092994046 |
Math.LOG2E |
log₂(e) 값 |
1.4426950408889634 |
Math.LOG10E |
log₁₀(e) 값 |
0.4342944819032518 |
Math.SQRT2 |
√2 값 |
1.4142135623730951 |
Math.SQRT1_2 |
1/√2 값 |
0.7071067811865476 |
3. Math.random()
을 활용한 난수 생성
1) 0 이상 1 미만의 랜덤 숫자
console.log(Math.random()); // 0.0 ~ 0.999999...
2) 특정 범위(예: 1~10)의 랜덤 정수 생성
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // 1~10 사이의 난수
3) 6개의 로또 번호 생성 (1~45 범위)
function generateLotto() {
const numbers = new Set();
while (numbers.size < 6) {
numbers.add(Math.floor(Math.random() * 45) + 1);
}
return [...numbers].sort((a, b) => a - b);
}
console.log(generateLotto()); // [5, 12, 23, 31, 40, 42] (랜덤 값)
4. Math.pow()
와 Math.sqrt()
를 활용한 거듭제곱 연산
1) Math.pow(x, y)
사용
console.log(Math.pow(2, 3)); // 2³ = 8
console.log(Math.pow(5, 4)); // 5⁴ = 625
2) Math.sqrt(x)
사용
console.log(Math.sqrt(25)); // √25 = 5
console.log(Math.sqrt(81)); // √81 = 9
5. Math.max()
와 Math.min()
을 활용한 배열 최댓값, 최솟값 찾기
1) 배열에서 최댓값 찾기
const numbers = [12, 45, 3, 22, 10];
console.log(Math.max(...numbers)); // 45
2) 배열에서 최솟값 찾기
console.log(Math.min(...numbers)); // 3
반응형
'Frontend > Javascript Typescript' 카테고리의 다른 글
[Javascript] 렉시컬 스코프와 클로저 (0) | 2025.03.25 |
---|---|
[Javascript, React] 참조형 데이터의 불변성, 얕은 복사와 깊은 복사의 이해 (0) | 2025.03.21 |
[Javascript] 페이지 로딩 후 스크립트 실행(defer, DOMContentloade, onload) (0) | 2025.03.20 |
[Javascript] 객체 생성자, 객체 리터럴, JSON (2) | 2025.03.20 |
[Javascript] 자주 쓰이는 배열 메서드(map(), filter() 등) (0) | 2025.03.19 |