yongfront 2024. 4. 10. 14:18
반응형
SMALL

for...of 문은 ES6(ECMAScript 2015)에서 도입된 반복문 구문입니다. 이터러블(iterable) 객체(배열, 문자열, Map, Set 등)에서 값을 가져와 반복할 때 사용됩니다.

구문

for (variable of iterable) {
// 코드 블록
}

  • variable: 각 반복에서 다음 값이 할당되는 변수
  • iterable: 반복되는 이터러블 객체(Array, Map, Set, String, TypedArray, arguments 객체 등)

예시

  1. 배열 반복
const arr = [10, 20, 30, 40];

for (const value of arr) {
  console.log(value);// 10, 20, 30, 40
}

  1. 문자열 반복
const str = 'hello';

for (const char of str) {
  console.log(char);// 'h', 'e', 'l', 'l', 'o'
}

  1. Map 반복
const map = new Map();
map.set('a', 1);
map.set('b', 2);

for (const [key, value] of map) {
  console.log(`${key}: ${value}`);// 'a: 1', 'b: 2'
}

  1. Set 반복
const set = new Set([1, 2, 3, 3, 2, 1]);

for (const value of set) {
  console.log(value);// 1, 2, 3 (중복 제거됨)
}

for...of 문은 일반적으로 for...in 문보다 더 간결하고 직관적입니다. 또한 for...of는 값만 반복하지만, for...in은 객체의 모든 프로퍼티(키)를 반복합니다.

for...of는 이터러블 객체에서만 사용할 수 있습니다. 일반 객체에서는 for...in을 사용하거나, Object.entries()나 Object.values()를 사용하여 객체를 이터러블로 변환해야 합니다.

728x90
반응형
LIST