[JS ES6] 순회와 이터러블

2022. 3. 28. 10:47·JavaScript/JS ES6+
728x90

ES6에서의 리스트 순회

 


// ES5
const list = [1, 2, 3];
for(var i = 0; i<list.length; i++) {
  console.log(list[i]); // 1 2 3
}

const str = 'abc';
for(var i = 0; i<str.length; i++) {
  console.log(str[i]); // a b c
}

// ES6
const list = [1, 2, 3];
for(const a of list) {
  console.log(a);
}

const str = 'abc';
for(const a of str) {
  console.log(a);
}

 

Array, Set, Map

 

Array

const arr = [1, 2, 3];
for(const a of arr) console.log(a); // 1 2 3


let iter1 = arr[Symbol.iterator]();
iter1.next(); // {value: 1, done: false}

for(const a of iter1) console.log(a); // 2 3

 

Set

const set = new Set([1, 2, 3]);
for(const a of set) console.log(a); // 1 2 3

console.log(set[1]); // undefined

 

Map

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);

for(const a of map) console.log(a); // ["a", 1], ["b", 2], ["c", 3]
for(const a of map.keys()) console.log(a); // a b c
for(const a of map.values()) console.log(a); // 1 2 3


var iter2 = map[Symbol.iterator]();
iter2.next();

console.log(a of iter2) console.log(a); // ["b", 2], ["c", 3]

 

array, set, map 은 js 내장객체로써, 이터러블/이터레이터 프로토콜을 따르고 있다.
이터러블 : 이터레이터를 리턴하는 Symbol.iterator 를 가진 값
이터레이터 : { value, done } 객체를 리턴하는 next() 를 가진 값
iterable/iterator protocol : 이터러블을 for...of, 전개 연산자 등과 함께 동작하도록 한 규약

728x90
저작자표시 (새창열림)

'JavaScript > JS ES6+' 카테고리의 다른 글

[JS ES6] 함수형 자바스크립트 기본기  (0) 2022.03.28
'JavaScript/JS ES6+' 카테고리의 다른 글
  • [JS ES6] 함수형 자바스크립트 기본기
gudwnsgur
gudwnsgur
IT
    250x250
  • gudwnsgur
    gudwnsgur
    gudwnsgur
  • 전체
    오늘
    어제
    • 분류 전체보기 N
      • 개발이야기
      • Spring N
        • 이슈 해결
      • JPA
        • spring data jpa
      • Java
        • Java의 정석
      • Kotlin
        • Kotlin In Action
        • Kotlin 정리
      • 대규모 시스템 설계 기초
      • JavaScript
        • JS ES6+
      • 면접
        • CS
      • SQLD
      • BE 개발
        • spring webflux
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    대규모 시스템 설계 기초
    cookie
    session
    HTTP
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
gudwnsgur
[JS ES6] 순회와 이터러블
상단으로

티스토리툴바