본문 바로가기

개발👩‍💻/프론트엔드

JS for 반복문(foreach, for..in, for..of)

728x90

🔑 키워드

object map set

forEach for..in for..of

❓ for in ? for of ? 뭐가 다르지 ? feat. forEach

Object를 iterator하게 사용하기 위해서 사용하는 반복문이 있다.

그 외에도 JS에서는 내장메서드인 forEach 가 있다.

해당 메서드 및 반복문의 사용방식과 차이점에 대해 알아보자 한다.

forEach 는 built-in object 내장 객체로 사용할 수 있는 컬랙션이 있다.

기존에는 Array 만 사용가능했지만, ES6 이후 부터는 Map Set 내에서도 사용할 수 있다.

  • Map (삽입 순서 유지)
forEach((value, key, map) => { /* … */ } [, thisArg])

기존 Arry forEach 의 형태를 살리기 위해 value 를 맨 앞에 두었다.

마지막 map 은 반복되고 있는 현재 map 객체를 의미한다.

  • Set (삽입 순서 유지)
forEach((value, key, set) => { /* … */ } [, thisArg])

Set forEach 또한 key 값을 받는 파라미터 부분이 있으나, 이는 value 와 같은 값을 의미한다.

  • 예시
    • Map
    function logMapElements(value, key, map) {
      console.log(`m[${key}] = ${value}`);
    }
    
    new Map([['foo', 3], ['bar', {}], ['baz', undefined]])
      .forEach(logMapElements);
    
    // expected output: "m[foo] = 3"
    // expected output: "m[bar] = [object Object]"
    // expected output: "m[baz] = undefined"
    
    • Set
    function logSetElements(value1, value2, set) {
      console.log(`s[${value1}] = ${value2}`);
    }
    
    new Set(['foo', 'bar', undefined]).forEach(logSetElements);
    
    // expected output: "s[foo] = foo"
    // expected output: "s[bar] = bar"
    // expected output: "s[undefined] = undefined"
    

for …in 반복문

  1. 모든 열거 가능한(Enumerable) 객체에서 사용 가능
  2. 반복문에서 객체의  값을 반복
  3. 순서를 보장하지 않음
  4. for ...in[[enumerble]] 값이 True 인 속성만 열거 가능
    1. built-in 메서드, built-in 프로퍼티 등 비열거형 속성 불가능
    2. obj.propertyIsEnumerable(str) 을 사용하여 확인 가능
  5. for ...in 은 상속 받은 모든 Enumerable 속성을 모두 열거한다.
    1. 자신의 속성 뿐 아니라 상속 받은 모든 열거형 속성을 반복할 수 있다.
    2. 그렇기 때문에 hasOwnProperty() 를 사용하여 구별할 필요가 있을 수 있다.

for …of 반복문

  1. ES6 버전 이후 나온 statement
  2. 반복 가능한 객체([Symbol.iterator] 속성을 가지는) 컬랙션 전용 반복문
    1. Ex) Array, String, Map, Set, Generator, Argument, NodeList와 같은 DOM 객체
  • 예시
    • Array, Set: value 값을 반복
    const arr = [1, 2, 3]
    for (let value of arr) console.log(value) // 1, 2, 3
    
    let iterable = new Set([1, 1, 2, 2, 3, 3]);
    
    for (let value of iterable) {
      console.log(value);
    }
    // 1
    // 2
    // 3
    
    • Map: Entries([key, value]) 반복
    let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
    
    for (let entry of iterable) {
      console.log(entry);
    }
    // [a, 1]
    // [b, 2]
    // [c, 3]
    
    for (let [key, value] of iterable) {
      console.log(value);
    }
    // 1
    // 2
    // 3
    
    • Generator: next() 메서드 사용하지 않고 사용 가능
    function* fibonacci() { // 생성기 함수
      let [prev, curr] = [1, 1];
      while (true) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
      }
    }
    
    for (let n of fibonacci()) {
      console.log(n);
      // 1000에서 수열을 자름
      if (n >= 1000) {
        break;
      }
    }
    

 

🍯  요약

forEach

forEach 메서드는 Array Map Set 에서 사용할 수 있다.

for … infor … of 의 차이점

  for in for of
when old new
where 열거 가능한 객체 반복 가능한 객체
how 객체의 상속받은 속성까지 열거 built-in 종류에 따라 반복 값 종류 변화
what 모든 열거 가능한 객체(순수 Object) 반복 가능 객체 컬랙션
why Object 를 형 변환 없이 반복할 때
(속성 상속 여부 확인 필요)
for in 의 불편한 부분 개선
forEach 사용 불가할 때

🔖참고자료

for..in for..of

자바스크립트 for in vs for of 반복문 정리

 

자바스크립트 for in vs for of 반복문 정리

ES6 공부하면서 for in 과 for of 차이점이 뭔지 궁금해서 찾아보다가 정리해보았습니다. 잘못된 부분이 있으면 커멘트 부탁드려요~ http://itstory.tk/entry/Javascript-for-in-vs-for-of-반복문 foreach 반복문 foreac

jsdev.kr

What does enumerable property mean in JavaScript? - GeeksforGeeks

 

What does enumerable property mean in JavaScript? - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

What is the difference between iterable and enumerable in JS? I am going through For/of and For/In loop and these terms are coming up frequently

 

What is the difference between iterable and enumerable in JS? I am going through For/of and For/In loop and these terms are comi

I am coming across terms Iterable and Enumerable while studying For/in and For/of loops. Objects are supposed be enumerable and we have to use For/in loop to loop over the properties of the object ...

stackoverflow.com

forEach

Map.prototype.forEach() - JavaScript | MDN

 

Map.prototype.forEach() - JavaScript | MDN

The forEach() method executes a provided function once per each key/value pair in the Map object, in insertion order.

developer.mozilla.org

Set.prototype.forEach() - JavaScript | MDN

 

Set.prototype.forEach() - JavaScript | MDN

The forEach() method executes a provided function once for each value in the Set object, in insertion order.

developer.mozilla.org

 

반응형