이전 시리즈 글 : 코드 최적화 - 1. this.~ 문의 사용 보러가기
이전 시리즈 글 : 코드 최적화 - 2. 유효성 검사 보러가기
이전 시리즈 글 : 코드 최적화 - 3. for문과 forEach문
개요
- 개요는 시리즈 1과 동일
- 이하에서는 간결한 코드 작성하는 몇 가지 팁 정리함
1. 삼항 연산자 ? :
- 조건에 따라 값을 선택하는 자바스크립트의 표현 식
// 기본 구조
(condition) ? trueExpression : falseExpression;
- 예시 코드 : 프로젝트에 적용
this._result.forEach( (res) => {
ctx.fillStyle = res.handedness === "Left" ? "Red" : "Blue"; // 조건식 쓸 때 왼쪽처럼 등호 2번 사용 가능!
ctx.strokeStyle = "White";
ctx.lineWidth = 2;
res.keypoints.forEach(keypoint => {
this._drawKeypoint(ctx, keypoint);
});
Object.keys(FINGER_INDICES).forEach(finger => {
const points = FINGER_INDICES[finger].map(idx => res.keypoints[idx]);
this._drawPath(ctx, points, false);
});
});
// 최솟값 찾기
const a = 5;
const b = 10;
const min = (a < b) ? a : b;
console.log(min); // 출력: 5
2. && 연산자 활용
- 값이 존재할 때만 출력
- 예시 코드
const message = "안녕하세요!";
message && console.log(message);
3. filter 문 활용
- 배열에서 특정 조건을 만족하는 값만 필터링
- filter 문은 배열에서만 사용 가능
- 예시 코드
const numbers = [1, 2, 3, 4, 5];
// 홀수만 필터링
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(oddNumbers); // 출력: [1, 3, 5]
'Backend > Node.js' 카테고리의 다른 글
[Asynchronous] 비동기 처리 - 2. Promise (1) | 2023.12.01 |
---|---|
[Asynchronous] 비동기 처리 - 1. 비동기와 콜백 (0) | 2023.12.01 |
[Coding-Practice] 코드 최적화 - 3. for문과 forEach문 (0) | 2023.11.30 |
[Coding-Practice] 코드 최적화 - 2. 유효성 검사 (0) | 2023.11.30 |
[Coding-Practice] 코드 최적화 - 1. this.~ (1) | 2023.11.30 |