본문 바로가기

자바스크립트

JavaScript 표준 내장 객체 - Math

 

 

abs (absolute)

console.log(Math.abs(7))
console.log(Math.abs(-7))
console.log(Math.abs(3.14))
console.log(Math.abs(-3.14))

console.log(Math.abs('7.35'))
console.log(Math.abs('-7.35'))

   - 숫자 데이터의 절댓값을 반환하는 메서드입니다.

   - 문자를 입력하여도 Number로 형변환하여 절댓값을 적용해줍니다.

 

 

 

 

 

ceil & floor & round

console.log(Math.ceil(3.141592))	// 4
console.log(Math.floor(3.141592))	// 3
console.log(Math.round(3.141592))	// 3

console.log(Math.round(3.141*10)/10)	// 3.1
console.log(Math.round(3.166*10)/10)	// 3.2

   - 각각 올림(ceil), 내림(floor), 반올림(round)한 숫자를 반환합니다..

 

 

 

 

max & min

console.log(Math.max(1,5,9,3,7)) 
console.log(Math.min(1,7,5,3,9))

const numbers = [10,128,12,49,7]
console.log(Math.max(...numbers)) 
console.log(Math.min(...numbers))

   - 가장 큰 숫자(max), 가장 작은 숫자(min) 를 반환하는 메서드입니다.

   - 전개연산자 ... 를 사용하여 간략하게 표현할 수도 있습니다

 

 

 

 

random

console.log(random())

function random(min,max){
    return Math.floor(Math.random * (max-min)) + min
}

   - 무작위 숫자 하나를 호출합니다.

   - 범위가 없다면 0 이상 1 미만의 무작위 난수를 호출합니다.

   - Math.floor와 함께 사용하여 일정 범위 내 Integer를 반환하는 random 함수를 만들 수 있습니다.