Programming language/javascript

forEach ( javascript 반복문 )

hello-world 2022. 6. 23. 13:51
728x90
반응형

forEach ( javascript 반복문 )

forEach()는 주어진 callback을 배열에 있는 각 요소에 대해 오름차순으로 한 번씩 실행.

삭제했거나 초기화하지 않은 인덱스 속성에 대해서는 실행하지 않는다. 

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

forEach 에서 처리 되는 매개변수

- callback 각 요소에 대해 실행할 함수. 
그리고 아래는 callback 함수에서 세 가지 매개변수를 받는다. 
 1. currentValue : 처리할 현재 요소.
 2. index  :  배열 인덱스.  옵셔널 처리 되어 있기에 선언 안해도 된다. 
 3. array : forEach()를 호출한 배열. 옵셔널 처리 되어 있기에 선언 안해도 된다. 

- thisArg : callback 바로 뒤에 2번째 매개변수로 callback을 실행할 때 this로 사용할 값.  옵셔널 처리 되어 있기에 선언 안해도 된다. 

 

 

아래는 forEach 를 쓸 때 주의 사항.

1. map() 과 reduce() 와는 달리 undefined 를 반환하기 때문에  메서드 체인의 중간에 사용할 수 없다. 

2. forEach()는 배열을 변형하지 않는다. 그러나 callback이 변형할 수는 있다.

3. 예외를 던지지 않고는 forEach()를 중간에 멈출 수 없다.  중간에 멈춰야 한다면 forEach() 사용하지 말고 일반 for 문을 사용.

혹은 방법에 따라 for of, for in, Array.prototype.every(), Array.prototype.some(), Array.prototype.find(), Array.prototype.findIndex() 등을 사용하면 된다. 

 

초기화하지 않은 값 생략 

- arraySpare = [1, 3, , 7] 에서 콤마 사이로 빈값 처리 된 부분은 생략 처리된다.

const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach(function(element){
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.

 

 

for문을 ---> forEach 로 변환 

const abcItems = ['a', 'b', 'c'];
const test = [];

// 이전
for (let i=0; i<abcItems.length; i++) {
  copy.push(abcItems[i]);
}

// 이후
items.forEach( (item)=>{
  copy.push(item);
});

 

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

 

Array.prototype.forEach() - JavaScript | MDN

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

developer.mozilla.org

 

728x90
반응형