JavaScript의 메소드들 중 forEach, map, for 메소드의 차이점을 알아보자.
for ([initialization]; [condition]; [final-expression]) statement
for은 초깃값부터 시작해서 증가 또는 감소하면서 조건에 맞게 순회하는 반복문이다.
break;를 사용하여 반복문을 중단시킬 수 있다.
for(let i=0;i<arr.length;i++){
console.log(arr[i]);
}
for(let x of arr){
console.log(x);
}
위의 코드는 같은결과인 배열의 원소를 출력한다.
// Arrow function forEach((element) => { ... } ) forEach((element, index) => { ... } ) forEach((element, index, array) => { ... } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function callbackFn(element) { ... }) forEach(function callbackFn(element, index) { ... }) forEach(function callbackFn(element, index, array){ ... }) forEach(function callbackFn(element, index, array) { ... }, thisArg)
forEach는 배열의 각 요소에 대해 (비동기)함수를 적용하여 반복한다.
비동기 함수인 callback 함수를 갖는다.
callback함수의 파라미터는 element(배열요소), index, array(배열전체)의 순이다.
// Arrow function map((element) => { ... } ) map((element, index) => { ... } ) map((element, index, array) => { ... } ) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function callbackFn(element) { ... }) map(function callbackFn(element, index) { ... }) map(function callbackFn(element, index, array){ ... }) map(function callbackFn(element, index, array) { ... }, thisArg)
map은 배열내 원소들을 (비동기)함수를 적용하여 반복하고, 반환한다.
위에서 언급한 forEach와 동일한 특징을 갖지만
forEach는 반환을 하지 못하고, map은 값을 반환한다는 차이점이 있다.
forEach로 작성된 코드를 map으로 변경해도 똑같이 적용된다.(이때는 return이 없다.)
아래의 3가지 방법을 모두 똑같은 결과를 수행한다.
const projects = [1,2,3,4,5];
//forEach사용
projects.forEach((project) => {
console.log(project);
});
//for..of사용
for(let project of projects){
console.log(project);
}
//for문 사용
for(let i=0;i<projects.length;i++){
project = projects[i];
console.log(project);
}
for은 단순 반복시에 사용하고
forEach, map은 배열을 순회할때 사용할 것을 권장한다.
다만 배열 순회 후 새로운 배열(리턴값)을 얻고 싶을때는 map을 사용하면 된다.