-
수학 함수 (abs, ceil, floor, round, sort)개발공부/JavaScript 2024. 1. 4. 14:35
평소에 프로그래머스 통해서 코딩 테스트 준비하고 있는데 가끔 헷갈리는 함수들이 있어 종류 별로 정리해보려고 한다.
먼저 수학 관련된 함수에 대해 알아보자.
(문제에서 자주 사용했던 함수들 위주 정리)
abs()
- 절대값 반환 (숫자의 부호를 무시하고, 크기만 나타내는 값)
- Math.abs(number);
let num1 = 2; let num2 = -2; let num3 = 2.5; Math.abs(num1); // 2 Math.abs(num2); // 2 Math.abs(num3); // 2.5
ceil()
- 주어진 숫자 x 이상의 최소 정수를 반환 (정수로 올림하는 함수)
- Math.ceil(number);
let num1 = 2; let num2 = -2; let num3 = 2.5; let num4 = 2.1; let num5 = -2.5; Math.abs(num1); // 2 Math.abs(num2); // -2 Math.abs(num3); // 3 Math.abs(num4); // 3 Math.abs(num5); // -2
floor()
- 주어진 숫자를 내림하여 반환 (주어진 숫자보다 작거나 같은 숫자 중 가장 큰 정수를 반화)
- Math.floor(number);
let num1 = 2; let num2 = -2; let num3 = 2.5; let num4 = 2.1; let num5 = -2.5; Math.abs(num1); // 2 Math.abs(num2); // -2 Math.abs(num3); // 2 Math.abs(num4); // 2 Math.abs(num5); // -3
round()
- 주어진 숫자를 반올림하여 반환
- Math.round(number);
let num1 = 2; let num2 = -2; let num3 = 2.5; let num4 = 2.1; let num5 = -2.5; Math.abs(num1); // 2 Math.abs(num2); // -2 Math.abs(num3); // 2 Math.abs(num4); // 2 Math.abs(num5); // -3
sort()
- 배열 요소를 정렬
let numbers = [2, 1, 4, 6, 5]; numbers.sort(); // 오름차순 정렬 [1,2,4,5,6] numbers.sort((a, b) => b - a); // 내림차순 정렬 [6,5,4,2,1]
728x90'개발공부 > JavaScript' 카테고리의 다른 글
[자바스크립트] 자료형 변경하기 (0) 2024.02.05 [자바스크립트] 배열과 집합 ([], set()) (0) 2024.01.31 [JavaScript]리프레시 토큰(Refresh Token) (2) 2024.01.09 빈 값 (null, undefined, undeclared, NaN) (1) 2023.12.27 JS에서 비동기적으로 코딩하기 (0) 2023.12.21