
자바스크립트 Math 객체는 수학 연산과 상수를 제공하는 내장 객체입니다. 다른 객체와 달리 생성자 함수가 없으며, 정적 메서드와 속성만을 제공합니다.
Math 객체는 다른 객체와 달리 new 키워드를 사용해서 새로운 인스턴스를 만들 수 없습니다.new Math()와 같은 방식으로 Math 객체를 생성할 수 없습니다.Math객체의 속성과 메서드들이 Math객체의 인스턴스를 생성하지 않고도 사용할 수 있다는것을 의미합니다.// Math 객체의 속성 사용 예제
console.log(Math.PI); // Math 객체의 원주율 속성
// Math 객체의 메서드 사용 예제
let absValue = Math.abs(-5); // 절대값 계산
console.log(absValue); // 5
let maxNumber = Math.max(1, 2, 3); // 주어진 숫자 중 가장 큰 값 반환
console.log(maxNumber); // 3
let randomValue = Math.random(); // 0 이상 1 미만의 임의의 난수 생성
console.log(randomValue); // 예: 0.123456789
Math 객체의 속성인 Math.PI와 메서드인 Math.abs(), Math.max(), Math.random()을 직접 호출할 수 있습니다. Math객체의 인스턴스를 생성할 필요 없이 Math 객체의 속성과 메서드를 사용할 수 있습니다. Math 객체는 정적(static) 프로퍼티와 메소드만을 제공한다.정적 프로퍼티는 객체 자체에 연결된 속성으로, 고정된 값을 가질 수 있고, 그 값이 변할 수도 있습니다. Math.PI는 고정된 값인 원주율을 나타내지만, 일부 객체들은 프로그램 실행 중에 값이 변할 수도 있습니다. Date.now()처럼 프로그램 실행 중에 값이 변할 수 도 있는 정적 프로퍼티도 존재합니다. 객체 이름에 .연산자를 통해 접근합니다.
// Math 객체의 정적(static) 프로퍼티
console.log(Math.PI); // 원주율을 출력합니다.
console.log(Math.E); // 자연 로그의 밑을 출력합니다.
객체 인스턴스를 생성하지 않고도 직접 호출할 수 있는 메서드입니다. 즉, 객체를 생성하지 않고도 함수를 호출하여 원하는 기능을 수행할 수 있습니다. Math.abs(x)는 Math라는 객체에 직접 연결된 함수로, 어떤 숫자 x의 절대값을 계산해주는 함수입니다. 객체 이름에 ()연산자를 통해 호출할 수 있습니다.
// Math 객체의 정적(static) 메소드 예제
// 인수의 절대값을 반환합니다.
console.log(Math.abs(-5)); // 5
console.log(Math.abs(3.14)); // 3.14
console.log(Math.abs(0)); // 0
console.log(Math.abs(-Infinity)); // Infinity
let randomValue = Math.random(); // 0 이상 1 미만의 난수를 반환합니다.
console.log(randomValue); // 예: 0.123456789
console.log(Math.random()); // 0.2316314316862087
console.log(Math.ceil()) // NaN
console.log(Math.ceil(1)) // 1
console.log(Math.ceil(1.2)) // 2
console.log(Math.ceil(1.7)) // 2
console.log(Math.ceil(2.2)) // 3
console.log(Math.ceil(-1.3)) // -1
console.log(Math.ceil(-3.3)) // -3
console.log(Math.ceil(-8.9)) // -8
x를 올림한 정수를 반환합니다.console.log(Math.floor(1)) // 1
console.log(Math.floor(1.777)) // 1
console.log(Math.floor(1.9)) // 1
console.log(Math.floor(2.2)) // 2
console.log(Math.floor(-1.2)) // -2
console.log(Math.floor(1.7)) // -2
console.log(Math.floor(-3.2)) // -4
x를 내림한 정수를 반환합니다.console.log(Math.round(1.4)); // 1
console.log(Math.round(1.555)); // 2
console.log(Math.round(2.777)); // 3
console.log(Math.round(3.444)); // 3
console.log(Math.round(-1.5)); // -1
console.log(Math.round(-1.6666)); // -2
console.log(Math.round(-1.1)); // -1
x를 내림한 정수를 반환합니다.console.log(Math.abs(-5)); // 5
console.log(Math.abs(3.14)); // 3.14
console.log(Math.abs(0)); // 0
console.log(Math.abs(-Infinity)); // Infinity
console.log(Math.max(10, 20, 5)); // 20
console.log(Math.min(10, 20, 5)); // 5