1.1 기본 개념
JavaScript에서의 Iterators와 iterables(이터러블)은 객체를 반복 가능하게 만드는 기본적인 개념이야. 이 개념들은 현대 JavaScript에서 특히 for...of
루프, spread operator, 구조 분해 할당 등에서 자주 사용되지. 이번 강의에서는 iterables와 iterators가 뭐고, 어떻게 작동하는지, 어떻게 만들고 사용하는지 살펴볼 거야.
Iterables (이터러블 객체)
이터러블 객체는 iteration protocol을 구현하는 객체를 말해. 이 객체는 [Symbol.iterator]
라는 특별한 메서드를 가지고 있어야 하고, 이 메서드는 iterator 객체를 반환해야 해.
Iterators (이테레이터)
이테레이터는 next()
메서드를 가진 객체로, 다음 두 개의 속성을 가진 객체를 반환해:
value
— 다음 요소의 값done
— 시퀀스가 끝났는지 여부를 나타내는 불리언 값 (true
면 끝남,false
면 아직 진행 중)
사용 예제를 살펴보자.
내장된 이터러블 객체
JavaScript에는 배열, 문자열, Set
, Map
같은 몇몇 내장된 이터러블 객체가 있어.
예제 1: 배열 이터레이션
const array = [1, 2, 3, 4, 5];
for (const item of array) {
console.log(item);
}
// 출력: 1 2 3 4 5
예제 2: 문자열 이터레이션
const string = 'hello';
for (const char of string) {
console.log(char);
}
// 출력: h e l l o
1.2 커스텀 이테레이터 만들기
iteration protocol을 구현하여 커스텀 이테레이터를 만들 수 있어 — next()
메서드를 만드는 것 말야.
예제 1: 이테레이터 생성하기
function createIterator(array) {
let index = 0;
return {
next: function() {
if (index < array.length) {
return { value: array[index++], done: false };
} else {
return { done: true };
}
}
};
}
const myIterator = createIterator([1, 2, 3]);
console.log(myIterator.next()); // { value: 1, done: false }
console.log(myIterator.next()); // { value: 2, done: false }
console.log(myIterator.next()); // { value: 3, done: false }
console.log(myIterator.next()); // { done: true }
이터러블 객체 만들기
객체가 이터러블이 되려면 [Symbol.iterator]
메서드를 구현해야 해. 이렇게 만드는데, 꽤 복잡한 명칭이야. 한번 만들어보자.
예제 2: 이터러블 객체 만들기
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
for (const value of myIterable) {
console.log(value);
}
// 출력: 1 2 3
1.3 내장 메서드
이터러블 객체를 다루기 위한 내장 메서드와 연산자에 대해 알아보자.
예제 1: Spread 연산자
Spread 연산자(...
)는 이터러블 객체를 복사하거나 병합할 때 사용할 수 있어.
const array = [1, 2, 3];
const newArray = [...array, 4, 5, 6];
console.log(newArray); // 출력: [1, 2, 3, 4, 5, 6]
예제 2: 구조 분해 할당
구조 분해 할당을 사용하여 이터러블 객체에서 값을 추출할 수 있어.
const [first, second, third] = [1, 2, 3];
console.log(first); // 출력: 1
console.log(second); // 출력: 2
console.log(third); // 출력: 3
예제 3: Array.from 및 Array.of 메서드
Array.from()
메서드는 이터러블 객체로부터 배열을 만들어.
const set = new Set([1, 2, 3, 4, 5]);
const array = Array.from(set);
console.log(array); // 출력: [1, 2, 3, 4, 5]
GO TO FULL VERSION