
반복, 순회라는 뜻으로 js는 iteration protocol을 따른다.
iteration protocol(순회 규칙)을 따르는 자료형에는 Array,String,Map,Set이 있고, 사용할 수 있는 연산자는 for..of, Spread가 있다.
iterable protocol을 만족하기 위해서는 객체안에 [Symbol.iterator]()이 있어야 하며 Iterator(반복자)프로토콜을 return해야 한다.
next(),return(), throw()메소드를 return하는 객체
done,value 프로퍼티를 가진 객체를 return한다.
const arr=[10,20,30];
for(const item of arr){
console.log(item);
}
// 10 ,20, 30
Array안에는 Symbol.iterator() 말고도 values(), keys(), entries()가 들어있다.
values()도 iterator 객체를 return한다.
const arr=[10,20,30];
const iterator =arr.values(); // Object [Array Iterator] {}
console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next().value)// 20
console.log(iterator.next()); // { value: 30, done: false }
console.log(iterator.next()); // { value:undefined , done: true}
iteration protocol을 따르지 않는 자료형(ex. Object)에 for..of같은 연산자를 쓰면 에러 발생.
그러나 객체에서 iteration protocol을 따르게 만들어 iterable하게 만들 수 있다.
객체를 iterable하게 만들려면 Symbol.iterator()와 next()값을 포함해야 한다.
const obj={
[Symbol.iterator](){ return
const min=0;
let num=10;
// Sybol.iterator()는 iterator 객체 return
return {
// iterator 객체안의 next()는 done,value 프로퍼티를 가진 객체 return
next(){
return{
done: num<min,
value: num-- % 2
}
}
}
}
};
for(const num of obj){
console.log(num); // 0 1 0 1 0 1 0 1 0 1 0
}