sitelink1  
sitelink2  
sitelink3  
sitelink4  
extra_vars4  
extra_vars5  
extra_vars6  

배열을 순회할 일이 많다

특히 json을 다룰 경우

그래서 for/in , for/of , forEach 에 대해 조사했다

 

서버로부터 boxes 라는 json 배열 문자열을 전달받는다

{"boxes":[{"name":"기본박스","items":[],"seq":1},{"name":"실온실","items":[{"qty":1,"name":"당근","seq":4},{"qty":5,"name":"사과","seq":5}],"seq":2},{"name":"냉장실","items":[{"qty":8,"name":"사과","seq":2}],"seq":3},{"name":"냉동실","items":[],"seq":4},{"name":"다용도실","items":[],"seq":5},{"name":"작은냉동실","items":[{"qty":1,"name":"소고기","seq":1}],"seq":6},{"name":"장난감함","items":[{"qty":1,"name":"퐁당핑","seq":3}],"seq":7}]}

 

전달받은 json 문자열(resMsg)을 js 에서 다음과 같이 파싱한다

let boxesJo = JSON.parse(resMsg)["boxes"];

 

이후 다음의 코드들은 모두 boxesJo 를 조회하며 Box Card 를 생성한다

 

[A] for in

for (idxb in boxesJo) {

    createBoxcard(boxesJo[idxb].name, null, boxesJo[idxb].items);

}

 

[B] for of

for (box of boxesJo) {

    createBoxcard(box.name, null, box.items);

}

 

[C] forEach

boxesJo.forEach(box => {

    createBoxcard(box.name, null, box.items);

});

 

for/in 과 for/of 의 차이점은 for/in 은 배열의 index 를 반환하고 for/of 는 배열내의 아이템 자체(오브젝트)를 반환한다

for/in 을 사용할 용도는 iterator 형태의 배열을 순회하기보다는 그냥 오브젝트 자체가 가진 속성들(Attributes)들을 순회할때 사용한다

 

가령 boxesJo.attr1 = "TEST"; 을 추가하고 for/in 을 순회하면 box 목록에는 "attr1" 도 포함되어 있게 된다

다음의 코드 예제를 다시 살펴보자

 

Object.prototype.objCustom = function () {};

Array.prototype.arrCustom = function () {};

 

let iterable = [3, 5, 7];

iterable.foo = "hello";

 

for (let i in iterable) {

  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"

}

 

for (let i of iterable) {

  console.log(i); // logs 3, 5, 7

}

 

번호 제목 글쓴이 날짜 조회 수
110 현재 document 의 host 와 port 를 얻는 방법 황제낙엽 2023.10.03 1
109 (Bard) FileReader 로 여러개의 파일을 read 하는 법 file 황제낙엽 2023.08.23 0
108 navigator.mediaDevices 황제낙엽 2023.08.21 1
107 Barcode Detection API 황제낙엽 2023.08.06 6
106 체크박스에 체크된 항목 개수 구하기 황제낙엽 2023.06.10 1
» 배열에 대한 루프문 조회 (loop iterator) 황제낙엽 2023.03.01 3
104 (Copilot) 바닐라 스크립트가 뭐지? 황제낙엽 2023.02.24 7
103 문자열에서 역슬래시(backslash) 문자와 유니코드(Unicode)에 대한 고찰 file 황제낙엽 2021.06.03 160
102 자바스크립트(Javascript) escape, encodeURI, encodeURIComponent 인코딩 함수 황제낙엽 2021.04.27 34
101 자바스크립트 학습용 유튜브 강의 (드림코딩 by 엘리) 황제낙엽 2021.03.07 119
100 Early return, early exit - 스크립트 가독성 개선 팁 황제낙엽 2021.03.07 19
99 [GitHub] JavaScript Algorithms and Data Structures (알고리즘과 자료구조) file 황제낙엽 2021.03.01 11
98 비동기프로그래밍 - 콜백함수(Callback function) file 황제낙엽 2020.08.26 33
97 Strict 모드 황제낙엽 2020.08.23 10
96 서비스 워커 file 황제낙엽 2020.05.25 177
95 경과 시간 구하기 황제낙엽 2019.10.04 1071
94 입력받은 날짜와 현재 날짜와의 비교 함수 황제낙엽 2019.08.02 499
93 사용자 모듈 만들기 황제낙엽 2019.07.09 41735
92 charcode 32와 160 차이 (javascript char 160 to 32) 황제낙엽 2019.05.11 55
91 부동소수점 (floating-point) file 황제낙엽 2018.03.26 1122