📒 JavaScript
ES6에서의 순회와 이터러블: 이터레이터 프로토콜
zunwon
2024. 1. 26. 18:57
기존과 달라진 ES6에서의 리스트 순회
- for i++
- for of
const list = [1, 2, 3];
for(let i = 0; i < list.length; i++) {
console.log(list[i]);
}
for(const a of list) {
console.log(a);
}
Array
const arr = [1, 2, 3];
for(const a of arr) {
console.log(a);
}
Set
const set = new Set([1, 2, 3]);
for ( const a of set) console.log(a);
Map
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const a of map) console.log(a);
이터러블/이터레이터 프로토콜
- 이터러블 : 이터레이터를 리턴하는 [Symbol.iterator]()를 가진 값
- 이터레이터 : { value, done } 객체를 리턴하는 next()를 가진 값
- 이터러블/이터레이터 프로토콜 : 이터러블을 for...of, 전개 연산자 등과 함께 동작하도록한 규약
사용자 정의 이터러블을 통해 알아보기
const iterable = {
[Symbol.iterator]() {
let i = 3;
return {
next() {
return i == 0 ? { done: true } : { value: i--, done: false };
},
[Symbol.iterator]() { return this; }
};
},
};
let iterator = iterable[Symbol.iterator]();
전개 연산자
const a = [1, 2];
console.log([...a]);
console.log([...arr, ...set, ...map.keys()]);