본문 바로가기
Front-End/javascript

[Javascript 기초] forEach(), map() 메소드

by 김기. 2023. 5. 9.

1. forEach() 메소드

forEach() 메소드는 배열의 요소를 반복하여 함수를 호출하며, 배열에서 루프를 돌 때 사용합니다.
forEach() 메소드는 ES5 문법이며, 반복 처리가 가능하고 DOM 반복이 가능한 유사배열입니다.


forEach() 메소드의 문법은 다음과 같습니다.
colors.forEach((currentValue, index, arr));


currentValue: 배열의 값
index: 현재 항목의 인덱스(선택사항)
arr: 현재 항목의 배열(선택사항)

const colors = ["black", "red", "blue"];

colors.forEach((currentValue, index, arr)=>{
  console.log(currentValue); // 배열값
  console.log(index); // 항목의 인덱스
  console.log(arr); // 항목의 배열
});

/* 출력
black
0
['black', 'red', 'blue']
red
1
['black', 'red', 'blue']
blue
2
['black', 'red', 'blue']
*/

 

2. map() 메소드

map() 메소드는 각 요소를 순회하면서, 콜백 함수를 호출하고 그 반환값을 새로운 배열의 요소로 추가합니다.

map() 메소드는 ES6 문법이며, 마찬가지로 반복이 가능하지만 DOM 반복은 불가능합니다.

*콜백 함수:  함수호출시 인수로 함수가 들어가는 형태

 

const colors = ["black", "red", "blue"];

colors.map((currentValue, index, arr)=>{
  console.log(currentValue);
  console.log(index);
  console.log(arr);
});

/* 출력
black
0
['black', 'red', 'blue']
red
1
['black', 'red', 'blue']
blue
2
['black', 'red', 'blue']
*/
const arr = [1, 2, 3, 4];

const modiArr = arr.map(el => el * 2);

console.log(modiArr); // 2, 4, 6, 8

댓글