본문 바로가기
공부_정리☆★

정리_JavaScript - 반복문 - forEach, for...of, for...in

by SKim입니다 2020. 6. 27.

var myString = "fruits"

 

var myArray = [ "Apple", "Banana", "Kiwi" ]

* element - index, value(element)

 

var myObj = {

 name: 'pikachu',

 color: 'yellow',

}

* property - key(name), value

forEach

- array, set, map에서 사용 가능

- array 안에 있는 각각의 element에 대하여 한번씩, 주어진 callback 함수를, 오름차순으로 실행시킨다.

- delete되거나 uninitalized된 index property에 대해서는 실행시키지 않는다.   ex) [ 1, 3, , 7 ] (sparse array)

- callback은 이 세 가지 argument에 대하여 실행될 수 있다.

  ① element의 value ② element의 index ③ traverse(횡단)되는 중인 array object

- exception을 throw함으로써 stop하거나 break할 수 없다. 만약 그러고 싶다면,

  for loop, for...of loop, for...in loop, every(), some(), find(), findIndex() 등을 사용하자.

 

구문: arr.forEach ( callback ( currentvalue [, index [, array ]])[, thisArg])

callback - 각각의 element에 대해서 실행할 함수. 다음의 1~3가지 argument를 받는다.

  ① currentValue - array 안의, 현재 처리되고 있는 element

  ② index (Optional) - ①의 index
  ③ array (Optional) - forEach()를 호출한 array
thisArg (Optional) - callback을 실행할 때 this로 사용할 value

 

myArray.forEach (element => console.log(element));

// Apple, Banana, Kiwi

 

function logArrayElements (element, index, array) {

 console.log ( 'a[' + index + '] = ' + element )

}

[2, 5, , 9].forEach(logArrayElements) // a[0] = 2 , a[1] = 5, a[3] = 9

 

 

 

for...of

- iterable objects에 대해서 iterate하는 loop를 생성한다.

- built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

- the value of each distinct property of the object에 대하여 custom iteration hook with statements를 실행시킨다.

 

장점

- array의 iterate를 지원하는 문법 중에서 가장 간결하고 직접적으로 접근 가능

- for...in 구문의 단점을 보완

- forEach 구문에서 지원하지 않는 return, break, continue 구문 사용 가능

 

for (var i of myString) { // value

 console.log(i)   // f, r, u, i, t, s

}

 

for (var i of myArray) { // value(element)

 console.log(i)   // Apple, Banana, Kiwi

}

 

for (var i of mySet) { // value

 console.log(i)   // Apple, Banana, Kiwi

}

 

for (var i of myObj) { // property

 console.log(i)   // pikachu, yellow

}

 

for (var i of myMap) { // entry

 console.log(i)   //  [name, pikachu], [color, yellow]

}

 

for (var [i, j] of myMap) { // key, value

 console.log(j)   // pikachu, yellow

}

 

myObject[Symbol.iterator] is not a function이라는 TypeError가 뜬다면

for (var i of Object.keys (myObject)) { // value

 console.log(i) // name, color

}

 

 

 

* for...of와 for...in의 차이

for...of - iterable object가 define하는 values에 대하여 iterate한다.

for...in - object의 enumerable properties에 대하여 무작위 순서로 iterate한다.

 

 

 

for...in

- object의, string인 key가 있는 모든 (상속된 것도 포함) enumerable(열거할 수 있는) property에 대하여 iterate한다.

- 순서는 무작위이다 → 순서가 중요하다면 forEach나 for..of를 사용한다.

- key가 symbol인 것은 무시한다.

- 내장 constructor에 의해 생성된 array나 object같은 object는, Object.prototype나 String.prototype로부터 상속받은 non-enumerable한 property(ex) String의 indexOf() 메소드나 Object의 toString() 메소드)를 가진다. 

- iteration 동안 property를 add, modify, remove하지 않는 것이 좋다.

 

단점이 많다.

- 인덱스가 string으로 return

- 루프 구문이 elemet들만 iterate하는 것이 아니라  프로토타입 chain도 iterate

  = javascript 내장함수들과 우리가 추가한 함수까지 나온다.

- 루프 iterate 순서가 무작위

 

→ 그런데도 쓰는 이유는? 디버깅에 주로 쓴다.

 

for (var i in myArray) { // number

 console.log(i)   // "0", "1", "2"

}

 

for (var i in myObj) { // property

 console.log(i)   // name, color

}

 

for (var i in myObj) { // key=prop

 console.log(i, myObj[i])   //  name pikachu, color yellow

}

 

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

 

Array.prototype.forEach()

forEach() 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

 

for...of

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statement

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

 

for...in

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

developer.mozilla.org

 

https://niceman.tistory.com/111

 

Javascript(ES6) - For in, For of loop(반복문) 설명 및 예제

ES6(ECMAScript 6) For문 설명 개발자에게 있어서 반복문을 활용하는 것은 정말 중요하다고 생각합니다. 잘못된 코딩 습관, 의미없는 요소 순회 및 객체 생성 등은 실행 환경에서 성능에도 지장을 주�

niceman.tistory.com

https://2dubbing.tistory.com/9

 

javascript의 for in과 for of

javascript에는 for in 과 for of가 있습니다. 이 둘의 공통적인 기능은 순회 할 객체의 길이만큼 반복을 한다는 점에서는 같습니다. 하지만, 서로 다른 부분이 존재한다고 합니다. 저도 최근에 프로젝�

2dubbing.tistory.com

 

댓글