[Javascript] forEach()

nana·2022년 10월 26일
0

JAVASCRIPT

목록 보기
1/3
post-thumbnail

forEach()

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

arr.forEach(func(current value, index, array))

📌 forEach와 Map의 차이점
forEach와 map은 배열을 순회하면서 배열의 각 원소들을 출력한다.
차이점이 있다면, map은 forEach와 달리 실행결과를 모은 새로운 배열을 리턴한다.


forEach 메서드를 사용해 배열을 순회하려면 콜백 함수 또는 익명 함수가 필요하고, 매개변수와 함께 전달해야 한다.

forEach 매개변수

  • Current Value : 처리할 현재 요소
  • Index : 처리할 현재 요소의 인덱스 (생략가능)
  • Array : forEach 메서드를 호출한 배열 (생략가능)

forEach 예시

const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => console.log(number)); // 화살표함수 사용

// 1
// 2
// 3
// 4
// 5

선택적 매개변수 사용

1) index

numbers.forEach((number, index) => {
    console.log('Index: ' + index + ' Value: ' + number);
});

// Index: 0 Value: 1
// Index: 1 Value: 2
// Index: 2 Value: 3
// Index: 3 Value: 4
// Index: 4 Value: 5

2) array

배열 매개변수는 원본 배열 그 자체이다. 단순히 호출하기만 하면 배열의 요소 수만큼 배열이 출력된다.

numbers.forEach((number, index, array) => {
    console.log(array);
});

// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]

Set에서 forEach()로 요소 순회

const set = new Set([1, 2, 3]);

set.forEach((item) => console.log(item));

// 1
// 2
// 3

Map에서 forEach()로 요소 순회

Map의 모든 요소를 순회하면서 value를 출력할 수 있다.

let map = new Map();
map.set('name', 'John');
map.set('age', '30');

map.forEach ((value) => console.log(value));

// John
// 30

key와 value를 함께 전달받을 수도 있다.

let map = new Map();
map.set('name', 'John');
map.set('age', '30');

map.forEach ((key, value) => console.log(key, value));

// name John
// age 30
profile
프론트엔드 개발자 도전기

0개의 댓글