본문 바로가기
도서로 공부하는 프로그래밍/코딩 자율학습

[NodeJS] 'for...of' 문과 'for...in' 문

by 열공노년 2024. 5. 30.
반응형

'for...of' 문

자바스크립트의 'for...of' 문은 반복 가능한(iterable) 객체를 순회할 때 사용되는 반복문입니다. 'for...of' 문은 배열, 문자열, Map, Set 등과 같은 반복 가능한 객체의 각 요소를 순회할 수 있습니다. 이는 자바스크립트의 다른 반복문인 'for', 'for...in' 문과는 다르게, 반복 대상의 값(value)을 직접 순회합니다.

구문

for (variable of iterable) {
  // 실행할 코드
}
  • variable은 각 반복에서 반복 가능한 객체의 다음 값을 할당받는 변수입니다.
  • iterable은 반복 가능한 객체입니다.

예제 1: 배열 순회

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

for (const number of numbers) {
  console.log(number);
}

VSCode에서 예제 실행

예제 2: 문자열 순회

const message = "Hello, World!";

for (const char of message) {
  console.log(char);
}

예제 2 실행

예제 3: Set 객체 순회

const uniqueNumbers = new Set([1, 2, 3, 4, 5]);

for (const number of uniqueNumbers) {
  console.log(number);
}

예제 3 실행

예제 4: Map 객체 순회

const user = new Map([
  ['name', 'John'],
  ['age', 30],
  ['city', 'New York']
]);

for (const [key, value] of user) {
  console.log(`${key}: ${value}`);
}

예제 4 실행

예제 5: NodeList 순회

const elements = document.querySelectorAll('div');

for (const element of elements) {
  console.log(element);
}

특징과 장점

  1. 값에 직접 접근: 'for...of' 문은 반복 가능한 객체의 각 값에 직접 접근할 수 있어서 코드가 더 간결하고 읽기 쉽습니다.
  2. 순회 가능한 객체: 배열, 문자열, Map, Set, NodeList 등 다양한 객체를 순회할 수 있습니다.
  3. 비교: 'for...in' 문은 객체의 속성을 순회할 때 사용되며, 배열을 순회할 때 인덱스를 반환하지만, 'for...of' 문은 값 자체를 반환합니다.

예제 6: 'for...of'와 'for...in'의 차이

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

// 'for...in' 문: 인덱스를 순회
for (const index in array) {
  console.log(index); // 0, 1, 2
}

// 'for...of' 문: 값을 순회
for (const value of array) {
  console.log(value); // 'a', 'b', 'c'
}

'for...of'와 'for...in'의 차이

 

정리

'for...of' 문은 자바스크립트에서 반복 작업을 수행할 때 매우 유용한 문법입니다. 반복 가능한 객체의 각 요소를 간편하게 순회할 수 있도록 도와주며, 코드의 가독성을 높여줍니다.

반응형