ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • for...of / for...in 에 대해서
    프론트엔드/JavaScript 2020. 9. 9. 23:09

    자바 스크립트 for문에는 'for...in'과 'for...of'가 있다.

     

    이 둘을 쓰면 일반 for문을 쓰는 것보다 편하게 for문 작성이 가능하다.

     

    <body>
        <script>
    
            let obj = { num1: 1, num2: 2, num3: 3, num4: 4, num5: 5 }
    
            let array = ['a','b','c','d','e']
    
            for (i of obj) {  // 객체의 for...of
                console.log(obj[i]);  // obj is not iterable 에러
                console.log([i]);  // obj is not iterable 에러
                console.log(i);  // obj is not iterable 에러
            };
    
            for (i of array) { // 배열의 for...of
                console.log(array[i]);  // undefined,undefined,undefined,undefined,undefined 출력
                console.log([i]);  // ["a", "b", "c", "d", "e"] 출력
                console.log(i);  // a,b,c,d,e 출력
            };
    
            for (i in obj) {  // 객체의 for...in
                console.log(obj[i]);  // 1,2,3,4,5 출력
                console.log([i]);  // ["num1", "num2", "num3", "num4"m "num5"] 출력
                console.log(i);  // num1, num2, num3, num4, num5 출력
            };
    
    
            for (i in array) {  // 배열의 for...in
                console.log(array[i]);  // a,b,c,d,e 출력
                console.log([i]);  // ["0", "1", "2", "3", "4"] 출력
                console.log(i);  // 0,1,2,3,4 출력
            };
    
        </script>
    </body>

     

    1. for...of / iterable 객체 순회 가능(주로 배열을 위해)

    <body>
        <script>
    
            let obj = { num1: 1, num2: 2, num3: 3, num4: 4, num5: 5 }
    
            let array = ['a','b','c','d','e']
    
            for (i of obj) {  // 객체의 for...of
                console.log(obj[i]);  // obj is not iterable 에러
                console.log([i]);  // obj is not iterable 에러
                console.log(i);  // obj is not iterable 에러
            };
    
            for (i of array) { // 배열의 for...of
                console.log(array[i]);  // undefined,undefined,undefined,undefined,undefined 출력
                console.log([i]);  // ["a", "b", "c", "d", "e"] 출력
                console.log(i);  // a,b,c,d,e 출력
            };
    
        </script>
    </body>

     

    'for...of'문은 반복할 수 있는 객체(iterable objects)를 순회할 수 있도록 해주는 반복문.

     

    자바스크립트에서 반복 가능한 객체는 Array, Map, Set, arguments 등이 있다.

     

    이 반복문은 루프마다 객체의 열거할 수 있는 프로퍼티의 값을 지정된 변수에 대입한다.

     

    즉 배열을 기준으로 순회하며 배열의 값을 돌려준다.

     

    'for...of'는 iterable하지 못한 객체를 순회할 수 없다.(리터럴 객체) 에러난다.

     

    간단히 이야기하면 배열의 경우 배열 안의 모든 수를 차례대로 끌어내는 역할을 한다.

     

    2. for...in / 해당 객체의 모든 열거할 수 있는 프로퍼티 순회 가능

    <body>
        <script>
    
            let obj = { num1: 1, num2: 2, num3: 3, num4: 4, num5: 5 }
    
            let array = ['a','b','c','d','e']
    
            for (i in obj) {  // 객체의 for...in
                console.log(obj[i]);  // 1,2,3,4,5 출력
                console.log([i]);  // ["num1", "num2", "num3", "num4"m "num5"] 출력
                console.log(i);  // num1, num2, num3, num4, num5 출력
            };
    
            for (i in array) {  // 배열의 for...in
                console.log(array[i]);  // a,b,c,d,e 출력
                console.log([i]);  // ["0", "1", "2", "3", "4"] 출력
                console.log(i);  // 0,1,2,3,4 출력
            };
    
        </script>
    </body>

     

    열거할 수 있는 프로퍼티란 내부적으로 enumerable 플래그가 true로 설정된 프로퍼티를 의미함.


    이러한 프로퍼티들은 for / in 문으로 접근할 수 있다.

     

    'for...in'은 객체는 물론이고 배열도 순회 가능하다.(보통 리터럴 객체에서 많이 쓴다)

     

    보통 이 방법은 객체에서 'key'값을 뽑아낼 때 많이 사용하게 된다.

     

    그리고 이 'key'값을 이용해 다양한 활용을 통해 값을 추출해낼 수 있다.

     

    다만 이는 배열에는 사용하지 않는 것이 좋다.

     

    그 이유는 순서를 보장할 수 없기 때문이다.

     

    그 이유는 'for...in'은 객체 순회를 위해 만든 것인데 객체는 근본적으로 순서가 없이 진행된다.

     

    반면 배열은 순서가 중요하다. 배열에는 'for...of'를 사용하는 것이 낫다.

    '프론트엔드 > JavaScript' 카테고리의 다른 글

    자바스크립트의 함수(function)  (0) 2020.09.10
    자바스크립트의 배열(Array)  (0) 2020.09.10
    자료형 변환(type conversion)  (0) 2020.09.09
    Var vs let vs Const  (0) 2020.09.09
    자바 스크립트의 데이터 타입  (0) 2020.09.05
Designed by Tistory.