TIL 012 | forEach( ), map( ) 메서드

김태규·2021년 8월 6일
0
post-thumbnail

1. forEach( ) 메서드

forEach 메서드는 주어진 함수를 배열 요소 각각에 대해 실행해주는 기능을 한다.

arr.forEach(callback(currentvalue, index, array))   // forEach 메서드의 문법

forEach 메서드는 파라미터로 콜백 함수를 받고, 콜백 함수의 파라미터는 배열의 요소, index, 순회 중인 배열 순서로 들어간다. 일반적으로 첫번째와 두번째 요소를 많이 사용한다.

let arr = [1, 2, 3, 4];

let valueAndIndex = function (value, index) {
  return console.log(`value = ${value} | index = ${index}`);
}

arr.forEach(valueAndIndex);  // "value = 1 | index = 0"
                             // "value = 2 | index = 1"
                             // "value = 3 | index = 2"
                             // "value = 4 | index = 3"

forEach 메서드의 특징 중 하나는 배열을 순회하면서 요소를 수정할 때 따로 바뀐 배열을 return하지 않는다는 것이다.

let number = [1, 2, 3, 4, 5];
let result = []; // forEach 메서드는 따로 배열을 return하지 않기 때문에 결과를 위한 배열을 미리 선언함

number.forEach(x => {
  result.push(x + 5);
});

console.log(result);   // [6, 7, 8, 9, 10]

위와 같이 화살표 함수를 이용하면 조금 더 간결하게 표현할 수도 있다.


2. map( ) 메서드

map 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 수행한 결과를 모아서 새로운 배열을 만들어 반환하는 메서드이다. forEach 메서드처럼 배열 내 요소들 순회하는데, 차이점은 주어진 함수를 각 요소에 대해 실행해주고 그 결과를 모아서 새로운 배열로 return 해준다는 점이다.

arr.map(callback(currentValue, index, array))  // map 메서드의 문법

map 메서드도 forEach 메서드와 같이 파라미터로 콜백 함수를 받고, 콜백 함수의 파라미터는 배열의 요소, index, 순회 중인 배열 순서로 들어간다.

let number = [1, 2, 3, 4, 5];

let result = number.map(x => {    // result에 새로운 배열이 할당됨
  return x + 5;
});

console.log(result);   // [6, 7, 8, 9, 10]
           

references

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://bigtop.tistory.com/57?category=800038
https://velog.io/@yunsungyang-omc/
https://bbaktaeho-95.tistory.com/32

0개의 댓글