[JS] forEach
구문
- Array, map, NodeList, set 등 다양한 자료구조의 prototype에 존재
- arr.forEach(callback[, thisArg]);
- 매개변수
- callback : 각 요소에 대해 실행할 함수, 다음 세 가지 인수를 받는다
- currentValue : 처리할 현재 요소
- index(optional) : 처리할 현재 요소의 인덱스
- array(optional) : forEach()를 호출한 배열
- thisArg(optional) : callback을 실행할 때 this로 사용할 값
- callback : 각 요소에 대해 실행할 함수, 다음 세 가지 인수를 받는다
- 매개변수
설명
- 주어진 callback을 배열에 있는 각 요소에 대해 오름차순으로 한 번씩 실행
- 삭제했거나, 초기화 하지 않은 인덱스 속성에 대해서는 실행하지 않음
- map(), reduce()와 달리 undefined 반환
특이사항
- 예외를 던지지 않고서는 forEach()를 중간에 멈출 수 없음
- 일반 반복문, for…of 반복문은 조기에 반복 종료 가능
- 반복 중에 배열이 변경되면 다른 요소들을 건너 뛸 수도 있다!
예제
- 일반적인 용법
const items = ['item1', 'item2', 'item3'];
const copy = [];
// 이전
for (let i=0; i<items.length; i++) {
copy.push(items[i]);
};
// 이후
itmes.forEach(function(item, index) {
console.log(item, index)
copy.push(item);
});
// item1 0
// item2 1
// item3 2
// copy = ['item1', 'item2', 'item3']
- 반복 중 배열 변경 시
var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
console.log(word);
if (word === 'two') {
words.shift();
}
});
// one
// two
// four
- thisArg 사용
- thisArg 매개변수 (this)를 forEach()에 제공, callback은 전달받은 this 값을 사용
function Counter() {
this.sum = 0;
this.count = 0;
};
Counter.prototype.add = function(array) {
array.forEach(function(entry) {
this.sum += entry;
++this.count;
}, this);
};
var obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3
obj.sum
// 16
출처 : MDN 문서
Date:
Tags:
JS