이전 시리즈 글 : 코드 최적화 - 1. this.~ 문의 사용 보러가기 

 


 

개요

  • 시리즈 1편 개요와 동일함.
  • 이하에서는 특정 값의 유효성을 검사하기 위한 코드인 ①if문 ②filter문을 정리함.

 


 

1. if

  • if문으로 유효성 검사 이유
    • 특정 객체가 undefined 또는 null 이 아닐 때만 코드 실행함
    • 따라서 예기치 못한 오류 방지하여 코드 안정성을 높이기 위해 수행
  • 예시 코드
// 예시 1
if (!this._detector) {
    this._createDetector().then(detector => {
        this._detector = detector;
        console.log("model loading success!, detector: ", this._detector);
    })
}

// 예시 2
if (!canvas || !this.isExistContent(this._result)) return canvas;

// 예시 3
if (this._result) {
  this._result.forEach( (res) => {
      ctx.fillStyle = res.handedness === "Left" ? "Red" : "Blue";
      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);
      });
  });
}

 


 

2. filter문

  • filter문으로 유효성 검사 이유
    • 배열에서 특정 조건을 만족하는 값만 필터링
    • filter 문은 배열에서만 사용 가능
  • 예시 코드
const numbers = [1, 2, 3, 4, 5];
// 홀수만 필터링
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(oddNumbers); // 출력: [1, 3, 5]

+ Recent posts