반응형

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);
});​

중간에 4가 배열에 추가되었지만 3까지 반복문이 도는 것을 확인.

  •  방문하기 전에 삭제된 요소에 대해서는 방문하지 않습니다.
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);
});

1의 차례에서 다음 index인 2가 삭제되자, 바로 3을 방문하는 것을 확인.

  • 인덱스를 기준으로 배열을 방문하기 때문에, 배열에 변동사항이 발생해 위치가 변동되면 건너뛰게 됩니다.
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()
  }
});	

2를 방문했을 때, 배열의 맨 앞 요소를 지움(shift)으로써 배열이 한 칸씩 앞당겨지고, 3을 건너뛰어 4를 방문함을 확인.

 


참고

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

 

 

반응형