1️⃣ Iterable Object
2️⃣ Iterator
3️⃣ Generator
Iteration이라는 영단어는 ‘반복’, Iterable이라는 영단어는 ‘반복 가능한’이라는 의미를 담고 있다.
JavaScript에서는 이전에 배웠던 Map
이나 Set
, Object
, Array
등과 같은 컬렉션을 순회하기 위한 Iteration Protocols(프로토콜, 약속, 규칙, 규약)이 정해져 있다.
for…of
문을 통해 데이터를 순회할 수 있으며 Spread(전개) 문법을 적용시킬 수 있다.Iterable Object는 Iterable Protocols의 규칙을 지키며, 반복이 가능한 객체라는 의미를 담고 있다.
Iterable은 일반 Object와 달리 Symbol.iterator
라는 메소드를 가지고 있다.
Iterable은 for…of
문에서만 반복할 수 있으며, Spread(전개 구문) 문법을 활용할 수 있다.
const arrayObject = [1, 2, 3];
for (let val of arrayObject) {
console.log(val);
}
// 1
// 2
// 3
const mapObject = new Map([["name","Shin"],["age",29]]);
for (let key of mapObject) {
console.log(key)
}
// (2) ['name', 'Shin']
// (2) ['age', 29]
const setObject = new Set("IVE");
for (let val of setObject) {
console.log(val)
}
// I
// V
// E
// 위에서 쓴 배열, Map 객체, Set 객체 모두 for...of 문으로 표현이 가능하므로 Iterable이다.
const normalObject = {"name":"Ahn", "age": 21}
console.log(Symbol.iterator in normalObject) // false - 일반 객체
console.log(Symbol.iterator in arrayObject) // true - Iterable
console.log(Symbol.iterator in mapObject) // true - Iterable
console.log(Symbol.iterator in setObject) // true - Iterable
for…of
반복문은 문자열에도 활용할 수 있다.for (let letter of "글자입니다") {
console.log(letter)
} // 글 자 입 니 다
Symbol.iterator
메소드를 호출해 반환되는 객체이다.