Iteration protocals

song·2023년 12월 10일
0

js 정보

목록 보기
23/30

Iteration protocols

  1. iterable protocol
  2. iterator protocol


iterable protocol

iterable하기 위한 충족 조건
: object는 iterator 메서드를 구현해야 함 (속성으로 Symbol.iterator을 가져야 함을 뜻함)

  • 사용자가 직접 만든 것이라도 iterable하다면 사용가능
  • 배열, 유사배열(NodeList, arguments), String, Map, Set은 모두 built-in interables이다

built-in interables의 프로토타입 객체들은 모두 iterator 메서드를 가짐



iterator protocol

  • 반환된 값은 객체이며 전달받는 매개변수가 없는 next 메서드를 가져야 함
  • next( )는 2개의 값(value, done)을 가진 객체를 반환해야 함
    value: done이 true일 경우 undefined를 적거나 생략될 수 있음
    done: boolean형태, 마지막 반복을 마치면 true, 반복할 작업이 남았다면 false


뜯어서 보는 iterable

// 배열은 iterable하다. 그렇다면 Symbol.iterator 메서드가 있어야 함
let fruit = ['apple', 'banana', 'cherry'];


console.log(typeof fruit[Symbol.iterator]); // function
// Symbol.iterator 타입이 function이라고 나왔다.


// 호출해보자
console.log(fruit[Symbol.iterator]()); // Object [Array Iterator] {}
// iterator가 담겨있다. 그럼 next 메서드가 있을 것이고 반환값은 value, done일 것이다.


// 변수에 담에 next를 호출해보자
let iter = fruit[Symbol.iterator]();
console.log(iter.next()); // { value: 'apple', done: false }
console.log(iter.next()); // { value: 'banana', done: false }
console.log(iter.next()); // { value: 'cherry', done: false }
console.log(iter.next()); // { value: 'undefined', done: true }


유사배열을 iterable하게 만들어 사용

유사배열: 배열처럼 생겼지만 배열이 아니기 때문에 배열의 메서드 사용 못 함
📍예외) NodeList, arguments는 iterable함

// 유사배열객체 newJeans
let newJeans = {
   0: '민지',
   1: '하니',
   2: '다니엘',
   3: '해린',
   4: '혜인',
   length: 5,
}


for (let x of newJeans) {
   console.log(x); // TypeError: newJeans is not iterable
}
// 유사배열객체를 Symbol.iterator 메서드를 추가해서 iterable하게 만들었다.
let newJeans = {
   0: '민지',
   1: '하니',
   2: '다니엘',
   3: '해린',
   4: '혜인',
   length: 5,
   [Symbol.iterator]() {
      const max = this.length;
      let i = 0;
      let val = this;

      return {
         next() {
            return { value: val[i++], done: i > max, };
         }
      };
   }
}


for (let x of newJeans) {
   console.log(x);
}
/* 
(출력값)
민지
하니
다니엘
해린
혜인
*/


정리

  • Symbol.iterator 메서드를 가지고 있다면 iterable protocol

  • Symbol.iterator 메서드 호출해서 나오는 것이 iterator protocol

  • iterator protocolnext메서드를 가짐.
    • next 메서드를 실행하면 valuedone이 객체를 반환
    • next 메서드는 반복이 끝날 때까지 연속적으로 값들을 출력해주는 시퀀스(연속된 값)가 설정되어있음
    • 마지막으로 반복이 마무리가 되면 done 값은 true, value 값은 undefined가 됨


iterable과 함께 사용되는 문법

  • for of
  • spread operator (...)
  • yield* (제너레이터)
  • destructuring assignment (구조분해 할당)


참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Iteration_protocols

profile
인간은 적응의 동물

0개의 댓글

관련 채용 정보