반응형

자바스크립트를 다루다 보면, 배열 내장 함수의 효율성과 간결성 때문에 자주 사용하게 돼. 하지만, break나 continue 같은 루프 제어문을 사용할 수 없다는 게 함정이지. 그럼 이 상황에서 어떻게 코드를 깔끔하고 효율적으로 작성할 수 있을까? 같이 알아보자.

forEach와 루프 컨트롤의 한계

forEach는 배열의 각 요소에 대해 함수를 실행하긴 하지만, break나 continue로 반복을 제어할 수 없어.

const array = [1, 2, 3, 4, 5];

array.forEach((element) => {
  if (element % 2 === 0) {
    console.log(element); // 2, 4
    // 여기서 break나 continue를 사용할 수 없어
  }
});

대안으로 for 또는 for...of 사용하기

for 또는 for...of 루프를 사용하면, 루프 중간에 탈출하거나 다음 반복으로 건너뛸 수 있어.

for (let i = 0; i < array.length; i++) {
  if (array[i] > 3) break;
  console.log(array[i]); // 1, 2, 3
}
for (const value of array) {
  if (value < 3) continue;
  console.log(value); // 3, 4, 5
}

filter와 map으로 깔끔하게 처리하기

filter와 map 메서드를 이용하면 continue의 필요성을 회피할 수 있어.

const filtered = array.filter((element) => element >= 3);
console.log(filtered); // [3, 4, 5]
const mapped = array.map((element) => element * 2);
console.log(mapped); // [2, 4, 6, 8, 10]

find와 some으로 특정 요소 다루기

find와 some 메서드는 조건에 맞는 요소를 찾아줘. find는 요소 자체를, some은 조건을 만족하는 요소가 있는지 여부를 반환해.

const found = array.find((element) => element > 3);
console.log(found); // 4
const hasLargeNumbers = array.some((element) => element > 3);
console.log(hasLargeNumbers); // true

마무리

자바스크립트 내장 배열 메서드를 사용할 때는 break와 continue의 한계를 알고 있어야 해. 다양한 메서드와 패턴을 알고 있으면 이런 제약 사항도 쉽게 해결할 수 있으니까!

반응형