✊ 필오의 개발일지
Back to Posts
2017년 11월 25일

9/ itertor

9/ itertor

타입스크립트 정리 글은 이웅재님의 강의 강의록 을 참고하여 작성하였습니다. (짱짱) 오류가 있다면 언제든지 댓글 부탁드립니다.

요약 아직 잘 이해가 안간다. 😵


1. for…of


2. for..in

일반적일때는 사용하지 않는 것으로. (엔진에 따라 다르다.)

const array = ['first', 'second']; const obj = { name: 'Mark', age: 35, }; // 배열에 for..of 이용 for (const item of array) { console.log(typeof item + ', ' + item); } // 배열에 for..in 이용 // item 이 string 타입의 숫자 for (const item in array) { console.log(typeof item + ', ' + item); } // 객체에 for..of 이용 => 오류 /* for (const item of obj) { console.log(typeof item + ', ' + item); } */ // 객체에 for..in 이용 for (const item in obj) { console.log(typeof item + ', ' + item); } // 객체의 keys 들에 for..of 이용 for (const item of Object.keys(obj)) { console.log(typeof item + ', ' + item); }

target 이 es3 인데도 forEach 는 트랜스파일이 되지 않았음. https://github.com/Microsoft/TypeScript/issues/2410 

const array = ['first', 'second']; // ts array.forEach(item => { console.log(item); }); // js array.forEach(function (item) { console.log(item); });

3. Symbol.iterator

이터러블(iterable)

iterate = 반복하다 이터러블은 순회 가능한 자료 구조이다. Symbol.iterator를 프로퍼티 key로 사용한 메소드를 구현하는 것에 의해 순회 가능한 자료 구조인 이터러블이 된다.

이터레이터

Symbol.iterator를 프로퍼티 key로 사용한 메소드는 이터레이터로 반환한다. 이터레이터는 순회 가능한 자료 구조인 이터러블의 요소를 탐색하기 위한 포인터로서 next() 메소드를 갖는 객체이다. next() 메소드는 value, done 프로퍼티를 갖는 객체를 반환하며 이 메소드를 통해 이터러블 객체를 순회할 수 있다.

ES6에서 제공하는 built-in iterable은 아래와 같다.


// lib.es6.d.ts interface IteratorResult<T> { done: boolean; value: T; } interface Iterator<T> { next(value?: any): IteratorResult<T>; // next가 필수로 있어야한다. return?(value?: any): IteratorResult<T>; throw?(e?: any): IteratorResult<T>; } interface Iterable<T> { [Symbol.iterator](): Iterator<T>; } interface IterableIterator<T> extends Iterator<T> { [Symbol.iterator](): IterableIterator<T>; }

5. CustomIterable

객체는 이터러블이 아니다. 하지만 이터레이션 프로토콜을 준수하여 이터러블 객체를 만들수 있다.

class CustomIterable implements Iterable<string> { private _array: Array<string> = ['first', 'second']; [Symbol.iterator]() { var nextIndex = 0; return { next: () => { return { value: this._array[nextIndex++], done: nextIndex > this._array.length, }; }, }; } } const cIterable = new CustomIterable(); for (const item of cIterable) { console.log(item); }

참고링크

  1. http://poiemaweb.com/es6-iteration-for-of 
Previous10/ Decorator
Next8/ Generic

Related

© 2025 Felix