이터러블이란 자료를 반복, 순회할 수 있는 객체를 뜻한다.
배열,문자열,map,set 도 이터러블 객체이다.
let arr = [1,2,3,4]
for(let item of arr) console.log(item)
// 1,2,3,4 가 정상적으로 출력이 된다.
arr[Symbol.iterator] = null
for(let item of arr) console.log(item)
//TypeError: arr is not iterable
위와 같이 arr는 이터러블 객체이기 때문에 for..of를 사용해 순회가 가능하다.
하지만 arr[Symbol.iterator] 을 null로 속성을 변경하면 더이상 이터러블이 아니기 때문에 for..of에서 에러가 나는 것을 알 수 있다.
obj는 이터러블이 아니기 때문에 배열처럼 순회,반복이 불가능하지만 [Symbol.iterator] 매서드를 추가해 이터러블 객체로 만들 수 있다.
let arr = {
num:0,
max: 10
}
for(let item of arr) console.log(arr)
//TypeError: arr is not iterable
let arr = {
num: 0,
max: 10,
[Symbol.iterator]() {
this.current = this.num;
return this;
},
next() {
return {
done: this.current * 2 > this.max,
value: this.current++ * 2,
};
},
};
for (let item of arr) console.log(item);
// 0,2,4,6,8,10
arr 객체에 [Symbol.iterator] 매서드를 추가해서 이터러블 객체로 만들 수 있다. 또한 이터러블 객체는 반드시 next()라는 매서드를 가지고 있어야 하는데,
next()는 done,value의 값을 가지고 있는 객체를 반환해 줘야 한다. value는 값을 반환하고 done은 순회가 끝난다면 true를 반환해 멈추도록 한다.(done이 true가 나오지 않는다면 끝나지 않는다)
❗Object.values(arr) , Object.keys(arr) , Object.entries(arr) 매서드를 사용해도 obj를 이터레이터로 바꿀 수 있다.
for..of을 사용할 수 있는 객체를 이터러블이라고 한다.