developer tip

자바 스크립트 : .forEach ()와 .map ()의 차이점

copycodes 2020. 9. 11. 08:11
반응형

자바 스크립트 : .forEach ()와 .map ()의 차이점


이런 주제가 많았다는 것을 알고 있습니다. 그리고 저는 기본을 알고 있습니다. .forEach()원래 어레이와 .map()어레이에서 작동합니다 .

나의 경우에는:

function practice (i){
    return i+1;
};

var a = [ -1, 0, 1, 2, 3, 4, 5 ];
var b = [ 0 ];
var c = [ 0 ];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);

그리고 이것은 출력입니다.

[ -1, 0, 1, 2, 3, 4, 5 ]
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
undefined
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
[ 0, 1, 2, 3, 4, 5, 6 ]

사용하는 이유를 이해할 수없는 practice변화의 가치 bundefined.
이 질문이 어리석은 질문이라면 미안하지만이 언어가 꽤 새롭고 지금까지 찾은 답변이 만족스럽지 않았습니다.


그들은 하나가 아니며 동일하지 않습니다. 차이점을 설명하겠습니다.

forEach: 목록을 반복하고 각 목록 구성원에 부작용이있는 일부 작업을 적용합니다 (예 : 모든 목록 항목을 데이터베이스에 저장).

map: 목록을 반복하고 해당 목록의 각 멤버를 변환하고 변환 된 멤버와 동일한 크기의 다른 목록을 반환합니다 (예 : 문자열 목록을 대문자로 변환).

참고 문헌

Array.prototype.forEach ()-JavaScript | MDN

Array.prototype.map ()-JavaScript | MDN


  • Array.forEach "배열 요소 당 한 번씩 제공된 함수를 실행합니다."

  • Array.map "이 배열의 모든 요소에 대해 제공된 함수를 호출 한 결과로 새 배열을 만듭니다."

따라서 forEach실제로 아무것도 반환하지 않습니다. 각 배열 요소에 대한 함수를 호출하면 완료됩니다. 따라서 호출 된 함수 내에서 반환하는 모든 것은 단순히 버려집니다.

반면에는 map각 배열 요소에 대해 유사하게 함수를 호출하지만 반환 값을 버리는 대신이를 캡처하고 해당 반환 값의 새 배열을 만듭니다.

This also means that you could use map wherever you are using forEach but you still shouldn’t do that so you don’t collect the return values without any purpose. It’s just more efficient to not collect them if you don’t need them.


+----------------+-------------------------------------+---------------------------------------+
|                | foreach                             | map                                   |
+----------------+-------------------------------------+---------------------------------------+
| Functionality  | Performs given operation on each    | Performs given "transformation" on    |
|                | element of the array                | "copy" of each element                |
+----------------+-------------------------------------+---------------------------------------+
| Return value   | Returns undefined                   | Returns new array with tranformed     |
|                |                                     | elements leaving back original array  |
|                |                                     | unchanged                             |
+----------------+-------------------------------------+---------------------------------------+
| Preferrable    | Performing non-transformation like  | Obtaining array containing output of  |
| usage scenario | processing on each element.         | some processing done on each element  |
| and example    |                                     | of the array.                         |
|                | For example, saving all elements in |                                       |
|                | the database                        | For example, obtaining array of       |
|                |                                     | lengths of each string in the         |
|                |                                     | array                                 |
+----------------+-------------------------------------+---------------------------------------+

The main difference that you need to know is .map() returns a new array while .forEach() doesn't. That is why you see that difference in the output. .forEach() just operates on every value in the array.

Read up:

You might also want to check out: - Array.prototype.every() - JavaScript | MDN


forEach: If you want to perform an action on the elements of an Array and it is same as you use for loop. The result of this method does not give us an output buy just loop through the elements.

map: If you want to perform an action on the elements of an array and also you want to store the output of your action into an Array. This is similar to for loop within a function that returns the result after each iteration.

Hope this helps.


The difference lies in what they return. After execution:

arr.map()

returns an array of elements resulting from the processed function; while:

arr.forEach()

returns undefined.


Performance Analysis For loops performs faster than map or foreach as number of elements in a array increases.

let array = [];
for (var i = 0; i < 20000000; i++) {
  array.push(i)
}

console.time('map');
array.map(num => {
  return num * 4;
});
console.timeEnd('map');


console.time('forEach');
array.forEach((num, index) => {
  return array[index] = num * 4;
});
console.timeEnd('forEach');

console.time('for');
for (i = 0; i < array.length; i++) {
  array[i] = array[i] * 2;

}
console.timeEnd('for');

One thing to point out is that foreach skips uninitialized values while map does not.

var arr = [1, , 3];

arr.forEach(function(element) {
    console.log(element);
});
//Expected output: 1 3

console.log(arr.map(element => element));
//Expected output: [1, undefined, 3];

Diffrence between Foreach & map :

Map() : If you use map then map can return new array by iterating main array.

Foreach() : If you use Foreach then it can not return anything for each can iterating main array.

useFul link : use this link for understanding diffrence

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f


Difference between forEach() & map()

forEach() just loop through the elements. It's throws away return values and always returns undefined.The result of this method does not give us an output .

map() loop through the elements allocates memory and stores return values by iterating main array

Example:

   var numbers = [2,3,5,7];

   var forEachNum = numbers.forEach(function(number){
      return number
   })
   console.log(forEachNum)
   //output undefined

   var mapNum = numbers.map(function(number){
      return number
   })
   console.log(mapNum)
   //output [2,3,5,7]

map() is faster than forEach()

참고URL : https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map

반응형