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
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
https://niceman.tistory.com/111
https://2dubbing.tistory.com/9
'공부_정리☆★' 카테고리의 다른 글
JavaScript_최소값과 합을 구하는 알고리즘에 대한 고찰 (작성중) (0) | 2020.06.29 |
---|---|
정리_JavaScript - 재귀함수 (Recursion) (0) | 2020.06.28 |
정리_JavaScript - 루프와 반복 - label, break, return, continue (0) | 2020.06.26 |
정리_정규표현식 (2) | 2020.06.26 |
정리_JavaScript/ES6 Collection - Set과 Map (0) | 2020.06.24 |
댓글