1. forEach 와 for of 의 차이

ES6 자바스크립트 forEach 와 for of 의 차이점
Feb 14, 2024
1. forEach 와 for of 의 차이
 

forEach:

  • 배열에 쉽게 접근할 수 있는 메서드로, 가독성이 높아 선호되는 경향이 있습니다.
const arr = [1, 2, 3]; arr.forEach(item => console.log(item));

for...of:

  • 최근에는 더 많은 사람들이 사용하고 있으며, 다양한 자료구조에 대해 반복할 때 유용합니다.
const arr = [1, 2, 3]; for (const item of arr) { console.log(item); }

for...of 문에서의 break와 continue

  • for...of 문에서는 forEach와는 다르게 break와 continue를 사용할 수 있습니다.
    • break: 반복문을 중단합니다.
    • continue: 다음 반복을 수행합니다.
const arr = [1, 2, 3]; for (const item of arr) { if (item === 2) break; console.log(item); }
 

Array.from 사용 여부

  • 최신 ES6 환경에서는 NodeList에도 forEach를 사용할 수 있지만, Array.from은 여전히 유용하게 사용됩니다.
  • 특히 유사 배열 객체나 배열 형태의 데이터를 진짜 배열로 변환할 때 사용됩니다
const nodeList = document.querySelectorAll('div'); const realArray = Array.from(nodeList);

arguments 객체

  • forEach를 사용하여 arguments 객체를 순회할 수 있습니다.
function example() { Array.from(arguments).forEach(arg => console.log(arg)); } example(1, 2, 3);

NodeList 순회

  • 최신 브라우저에서는 NodeList도 forEach를 사용하여 순회할 수 있습니다.
const nodeList = document.querySelectorAll('div'); nodeList.forEach(node => console.log(node));
Share article

꼬질꼬질