저장을 습관화

230530 TIL 본문

공부/TIL

230530 TIL

ctrs 2023. 5. 30. 21:46

1. Math

Math.ceil() 소수점 올림

Math.ceil(.95);    // 1
Math.ceil(4);      // 4
Math.ceil(7.004);  // 8
Math.ceil(-0.95);  // -0
Math.ceil(-4);     // -4
Math.ceil(-7.004); // -7


Math.floor() 소수점 내림

Math.floor( 45.95); //  45
Math.floor( 45.05); //  45
Math.floor(  4   ); //   4
Math.floor(-45.05); // -46
Math.floor(-45.95); // -46


Math.round() 소수점 반올림

Math.round( 20.49); //  20
Math.round( 20.5 ); //  21
Math.round( 42   ); //  42
Math.round(-20.5 ); // -20
Math.round(-20.51); // -21

 

Math.trunc() 소수점을 아예 버림

Math.trunc(13.37);    // 13
Math.trunc(42.84);    // 42
Math.trunc(0.123);    //  0
Math.trunc(-0.123);   // -0
Math.trunc('-1.123'); // -1
Math.trunc(NaN);      // NaN
Math.trunc('foo');    // NaN
Math.trunc();         // NaN

 

2. Math.trunc() VS Math.floor()

 

Math.trunc()는 소수점 이하는 다 버린다. 

Math.trunc(23.3) = 23
Math.trunc(-23.3) = -23


Math.floor()는 소수점을 내림한다. 

Math.floor(23.3) = 23
Math.floor(-23.3) = -24

단순히 소수점을 이하 수를 없애고 싶을때는 Math.trunc를 사용하는 것이 좋다.

 

 

3. ~~ (double tilde)

~ (tilde)는 not의 의미를 가지는 비트 연산자이다.

 

10진수 5를 16비트 2진수로 표시했을때
0000000000000100 이며

~5를 하면
1111111111111011이 된다. (-6)

~를 처리하는 과정에서 소수점은 버려지게 된다.

다시 한번 더 ~를 준다면 ~~5가 되어
0000000000000100이 되므로 (5)
결과적으로 Math.floor()와 같은 기능을 하게 된다.

이 과정에 대해서는 좀 더 공부가 필요할것 같다.

math.floor()와 비교했을때
장점
특정 브라우저 환경에서 math.floor나 parsInt보다 빠른 퍼포먼스를 보여준다

단점
일부 환경에선 오히려 느린 경우도 있다.
유지보수하는 입장에서 문맥의 이해가 어려울 수 있다.

 

 

4. 배열의 forEach

forEach() 메소드는 배열의 각 요소를 한번씩 사용하는 기능이다.

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
var numbers = [10, 20, 3, 16, 45];

numbers.forEach(function (number, index) {
console.log(index + "번째 값 => " + number);
});

// 실행 결과: 
// 0번째 값 => 10
// 1번째 값 => 20
// 2번째 값 => 3
// 3번째 값 => 16
// 4번째 값 => 45

위 코드에서 사용된 화살표 함수를 풀어쓰면 아래와 같다.

var numbers = [10, 20, 3, 16, 45];

function printElement(number, index) {
console.log(index + "번째 값 => " + number);
});

function printArray() {
numbers.forEach(printElement);
}

printArray();

// 실행 결과: 
// 0번째 값 => 10
// 1번째 값 => 20
// 2번째 값 => 3
// 3번째 값 => 16
// 4번째 값 => 45

아직도 화살표 함수가 익숙해지질 않는다...

 

[참고]

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

 

Array.prototype.forEach() - JavaScript | MDN

forEach() 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.

developer.mozilla.org

 

 

5. 배열 내 최대값과 최소값 구하기

5-0. Math.max(), Math.min()

배열이 아닌 상황에서 최대값 혹은 최소값을 구할때

let maxValue = Math.max(1, 2, 3, 4, 5);
let minValue = Math.min(1, 2, 3, 4, 5);

console.log(maxVlue, minValue);
// 5 1

 

5-1. Function.prototype.apply

let arr = [1, 2, 3, 4, 5];
let maxValue = Math.max.apply(null, arr);
let minValue = Math.min.apply(null, arr);

console.log(maxVlue, minValue);
// 5 1

apply() 메소드의 첫번째 파라미터로는
Math.max(), Math.min() 함수 내부에서 사용할 this 객체를 전달해야하는데,

여기서는 따로 this 객체를 지정해 줄 필요가 없으므로 null을 전달한다.

 

5-2. ... (spread operator, 전개 연산자)

let arr = [1, 2, 3, 4, 5];
let maxValue = Math.max(...arr);
let minValue = Math.min(...arr);

console.log(maxVlue, minValue);
// 5 1

console.log(...arr)
// 1 2 3 4 5

(...arr)은 배열 arr을 spread, 펼친다는 의미이다.

즉, Math.max(...arr); 은 Math.max(1, 2, 3, 4, 5); 와 같은 의미가 된다.

하지만 배열의 형태가 아닌 정수로써 나오게 되니 다시 한번 배열로 사용하려면 별도의 가공이 필요하다.

 

[참고]
https://hianna.tistory.com/487

 

[Javascript] 배열에서 최대값, 최소값 구하기

Javascript 배열의 여러 원소들 중 최대값, 최소값을 구하는 방법을 정리합니다. 1. Math.max(), Math.min() 소개 2. Function.prototype.apply() 사용하기 3. Spread Operator(전개 연산자) 사용하기 1. Math.max(), Math.min()

hianna.tistory.com

 

6. Math.random()

0 이상 1 미만의 무작위의 수를 구할때 쓴다.

console.log(Math.random());
// 실행 결과: 0.3224281163901015
// 실행 결과: 0.9852417449262711
// 실행 결과: 0.020739976630962387

이 상태로는 못 쓰니 가공한다.

예를 들어 0 이상 100 미만의 무작위의 수를 구하고 싶다면?

console.log(Math.random()*100);
// 실행 결과: 12.83669834193375
// 실행 결과: 19.21720890102463
// 실행 결과: 94.32145181020869

0 부터 100 까지의 수를 구하고 싶다면 101을 곱해주면 된다.

 

정수만을 사용하고 싶다면 Math.trunc() 메소드를 사용하면 된다.

console.log(Math.trunc(Math.random()*101));
// 실행 결과: 23
// 실행 결과: 55
// 실행 결과: 79

 

7. * 곱셈 연산자와 ** 제곱 연산자

console.log(3*3); // 9
console.log(3**3); // 27

이런게 있는지 오늘 알았다

멍청하게 3*3*3 하고 있었네

간단해서 외우기도 쉽고 유용하게 쓸수 있을것 같다.

'공부 > TIL' 카테고리의 다른 글

230607 TIL  (0) 2023.06.08
230606 TIL - 모듈 Module (2)  (0) 2023.06.06
230605 TIL - 모듈 Module  (0) 2023.06.05
230602 TIL  (0) 2023.06.02
230601 TIL  (0) 2023.06.02