
ECMAScript2015(ES6)에서 도입되었으며, 새로운 syntax가 아닌 몇 가지 규칙에 따라 모든 객체에 구현될 수 있는 규약입니다.
❶ Iterable protocol
❷ Iterator protocol
Iterable protocol을 만족하는 반복 가능한 객체(Iterable Object)를 의미합니다.
❶ Symbol.iterator (= @@iterator) method가 구현되어 있어야 한다.
❷ Symbol.iterator method는 Iterator를 반환해야 한다.
for...of처럼 객체의 반복이 시작되면 @@iterator method는 인자 없이 호출됩니다.Symbol.iterator에 들어있는 함수는 메서드로서 실행되기 때문에 this로 iterable 객체의 property에 접근이 가능합니다.yield를 이용해 각 entry를 제공할 수 있습니다.ES9에서 추가되었으며, promise를 반환한다는 것만 다르다.
❶ Symbol.asyncIterator method가 구현되어 있어야 한다.
❷ Symbol.asyncIterator method는 asyncIterator를 반환해야 한다.
const iterable = {};
iterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
}
console.log([...iterable]); // [1, 2, 3]
Intl.Segmeter 객체의 segment() method 호출 시 return됨function* gen() {
yield* ["a", "b", "c"];
}
console.log(gen().next()); // { value: "a", done: false }
❶ 객체가 next() method를 가져야 한다.
❷ next() method는 IteratorResult interface를 구현한 객체를 반환하는 0 또는 1개의 인자를 가지는 함수이다.
모든 iterator protocol method들(next, return, throw)은 IteratorResult interface를 구현한 객체를 반환해야 합니다.
done과 value property를 가지는 객체입니다.
false, 반복이 완료되었을 경우 trueAsync iterable protocol과 마찬가지로 ES9에서 추가되었으며, promise를 반환한다는 것만 iterator protocol 과의 차이점입니다.
❶ 객체가 next() method를 가져야 한다. (동일)
❷ next() method는 promise를 반환하는 0 또는 1개의 인자를 가지는 함수이다.
❸ fulfilled promise가 IteratorResult interface를 구현한 객체이다.
function makeIterator(array) {
let nextIndex = 0;
return {
next() {
return nextIndex < array.length
? {
value: array[nextIndex++],
done: false,
}
: {
done: true,
};
},
};
}
const it = makeIterator(["yo", "ya"]);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
iterator면서 iterable인 객체를 말합니다.
@@iterator method가 존재하고 해당 method가 자기자신(iterator)을 return 하는 것을 말합니다.
Non-well-formed iterable은 반대로 @@iterator method가 iterator 객체를 반환하지 않는 경우입니다.
| Iterable | Array-like |
|---|---|
Symbol.iterator method가 존재 | 인덱스와 length property 존재 |
문자열의 경우 둘 다에 해당합니다.
Related Content
JavaScript Generator
[JS] ECMAScript 자세히 알아보기