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 사용자 모듈 만들기 황제낙엽 2019.07.09 41735
109 User Agent 정보 모음 file 황제낙엽 2011.02.22 7768
108 페이지 스크롤 끝 확인 황제낙엽 2011.10.24 6230
107 ActiveX 설치 여부를 검사하는 스크립트 황제낙엽 2011.02.13 4053
106 브라우저의 새로고침과 종료에 대한 이벤트 황제낙엽 2017.08.11 2725
105 부동소수점 (floating-point) file 황제낙엽 2018.03.26 1122
104 javascirpt IME-Mode 설정하기 황제낙엽 2010.08.17 1112
103 경과 시간 구하기 황제낙엽 2019.10.04 1071
102 각 브라우저 별 User Agent 정보 황제낙엽 2011.02.22 823
101 자바스크립트의 쉬프트 연산자 (Shift Operator) 와 음수 (Negative) 이야기 황제낙엽 2012.05.31 726
100 iframe auto resize (cross browsing) 황제낙엽 2011.05.13 658
99 입력받은 날짜와 현재 날짜와의 비교 함수 황제낙엽 2019.08.02 500
98 url encode & decode 황제낙엽 2011.10.30 469
97 자바스크립트로 서버의 XML파일을 접근 (실패했슴) 황제낙엽 2005.12.11 444
96 Javascript 내장객체 String 황제낙엽 2007.04.10 392
95 JavaScript Touch and Gesture Events iPhone and Android 황제낙엽 2012.04.12 337
94 unshift() Method 황제낙엽 2009.03.02 287
93 Jasmine 테스트 및 CI 구축 가이드 황제낙엽 2016.11.16 254
92 Why does this simple Javascript prototype not work in IE? 황제낙엽 2011.03.24 242
91 브라우저에서 뒤로 가기 막기와 펑션키(function key) 막기 황제낙엽 2005.10.21 236