반응형
foreach
- Array객체에서만 사용이 가능합니다.(ES6부터는 Map, Set 등에서도 지원)
- callback함수를 등록하여 각 요소들이 반복될 때 callback함수를 호출합니다.
- 현재 요소값(currentvalue), 인덱스(index), array(foreach를 호출한 배열)의 값을 인자로 받을 수 있습니다.
let array = [1,2,3];
array.forEach((element,index,array) => {
console.log(element);
console.log(index);
console.log(array);
});
- 최초 callback함수 호출 전 설정된 요소에 대해서만 방문합니다.(foreach 반복 중간에 추가된 요소에 대해서는 방문X)
let array = [1,2,3];
array.forEach((element,index,array) => {
if(element % 2 == 0){
array.push(element+2);
}
console.log(element);
console.log(index);
console.log(array);
});
- 방문하기 전에 삭제된 요소에 대해서는 방문하지 않습니다.
let array = [1,2,3];
array.forEach((element,index,arr) => {
if(array[index+1] % 2 == 0){
array.splice(index+1,1);
}
console.log(element);
console.log(index);
console.log(array);
});
- 인덱스를 기준으로 배열을 방문하기 때문에, 배열에 변동사항이 발생해 위치가 변동되면 건너뛰게 됩니다.
let array = [1,2,3,4];
array.forEach((element,index,arr) => {
console.log(element);
console.log(index);
console.log(arr);
if (element === 2) {
arr.shift()
}
});
참고
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
반응형
'기술 정리 > Javascript' 카테고리의 다른 글
POST API status 201인 응답이 fail 콜백을 호출하는 이유(feat. dataType) (0) | 2023.11.13 |
---|---|
이벤트 버블링과 캡처링: 웹 이벤트 전파 메커니즘 (0) | 2023.09.12 |
ResizeObserver : Element의 크기 변화 감지 (1) | 2023.08.29 |