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

}

 

번호 제목 글쓴이 날짜 조회 수
114 [검토 완료] 디바이스 카메라로 촬영한 사진을 서버에 업로드하기 샘플 황제낙엽 2024.11.21 310
113 브라우저에서 이미지를 편집(crop 등) 할 수 있는 오픈소스 Cropper.js 황제낙엽 2024.11.16 341
112 DOMContentLoaded 이벤트와 window.onload 이벤트 황제낙엽 2024.07.15 231
111 [Copilot] Vanilla JavaScript에서 외부 스크립트 파일에 정의된 함수들을 로드 황제낙엽 2024.06.21 275
110 [Copilot] ES6 모듈(module) 문법 황제낙엽 2024.06.21 219
109 현재 document 의 host 와 port 를 얻는 방법 황제낙엽 2023.10.03 670
108 (Bard) FileReader 로 여러개의 파일을 read 하는 법 file 황제낙엽 2023.08.23 469
107 navigator.mediaDevices 황제낙엽 2023.08.21 294
106 Barcode Detection API 황제낙엽 2023.08.06 513
105 체크박스에 체크된 항목 개수 구하기 황제낙엽 2023.06.10 497
» 배열에 대한 루프문 조회 (loop iterator) 황제낙엽 2023.03.01 560
103 (Copilot) 바닐라 스크립트가 뭐지? 황제낙엽 2023.02.24 264
102 문자열에서 역슬래시(backslash) 문자와 유니코드(Unicode)에 대한 고찰 file 황제낙엽 2021.06.03 494
101 자바스크립트(Javascript) escape, encodeURI, encodeURIComponent 인코딩 함수 황제낙엽 2021.04.27 446
100 자바스크립트 학습용 유튜브 강의 (드림코딩 by 엘리) 황제낙엽 2021.03.07 467
99 Early return, early exit - 스크립트 가독성 개선 팁 황제낙엽 2021.03.07 373
98 [GitHub] JavaScript Algorithms and Data Structures (알고리즘과 자료구조) file 황제낙엽 2021.03.01 320
97 비동기프로그래밍 - 콜백함수(Callback function) file 황제낙엽 2020.08.26 437
96 Strict 모드 황제낙엽 2020.08.23 342
95 경과 시간 구하기 황제낙엽 2019.10.04 1414