자바스크립트의 배열 내장 메서드 forEach()
와 map()
은 주어진 함수를 각각의 요소에 대하여 실행한다는 점, 원본 배열 값이 변경되지 않는 점에서 공통점을 갖고 있지만 반환값이 다르다.
forEach()
: undefinedmap()
: 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열.const array1 = ['a', 'b', 'c'];
const result = array1.forEach(element => console.log(element));
console.log(result);
// expected output: "a"
// expected output: "b"
// expected output: "c"
// expected output: undefined
위 코드 예제에서는 forEach
의 매개변수로 주어진 콜백함수에 따라, array1
의 각 요소('a', 'b', 'c')가 순서대로 매개변수(element
)로 전달되어 콘솔에 출력된다.
result
에는 undefined
가 저장된다.
forEach()
의 경우 초기화되지 않은 요소는 반복 대상에서 제외시킨다.
아래 예제 코드를 살펴보자
const arraySparse = [1,3,,7];
let nums = 0;
for (let i = 0; i < arraySparse.length; ++i) {
nums2 += arraySparse[i];
}
console.log(nums2); //NaN
arraySparse
의 초기화 되지 않은 2번 index
도 반복문 대상에 포함된다.2번 index
에는 undefined
가 저장되어있으므로 이를 숫자에 더하는 순간 값이 NaN
이 되어 버린다.const arraySparse = [1,3,,7];
let nums = 0;
arraySparse.forEach(e => nums += e);
console.log(nums); // 11
2번 index
는 반복 대상에서 제외되기 때문에 0, 1, 3번 index를 더한 값인 11이 nums에 저장되어 있다.const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
map
함수는 각 요소 (1, 4, 9, 16)에 대하여 차례대로 2를 곱한 후 그 값을 새로운 배열 map1
에 저장한다.array1
은 변경되지 않는다.