본문 바로가기

자바스크립트 끄적끄적

forEach() 이용 정리

728x90

forEach()는 배열을 순회하면서 인자로 전달한 함수를 호출하는 반복문입니다. 배열 뿐만 아니라, Set이나 Map에서도 사용 가능!

1. forEach() 문법

forEach()의 문법은 아래와 같으며, 함수로 value, index, array를 전달할 수 있습니다.

arr.forEach(func(value, index, array))
  • value : 현재 순회 중인 요소
  • index : 현재 순회 중인 요소의 index
  • array : 배열 객체

 

예시)

실행

const arr = ['손흥민', '케인', '쿨쿨이', '페리시치'];

arr.forEach((item, index, arr) => {
  console.log("index: " + index + ", item: " + item
      + ", arr[" + index + "]: " + arr[index]);
});

결과

index: 0, item: 손흥민, arr[0]: 손흥민
index: 1, item: 케인, arr[1]: 케인
index: 2, item: 쿨쿨이, arr[2]: 쿨쿨이
index: 3, item: 페리시치, arr[3]: 페리시치
728x90