foreach와지도 사이에 차이가 있습니까?
자, 이것은 특정 언어를 기반으로 한 질문보다 컴퓨터 과학 질문에 가깝지만 맵 작업과 foreach 작업 사이에 차이가 있습니까? 아니면 그들은 같은 것에 대해 단순히 다른 이름입니까?
다른.
foreach는 목록을 반복하고 부작용이있는 일부 작업을 각 목록 멤버에 적용합니다 (예 : 데이터베이스에 각 항목을 저장하는 등).
map은 목록을 반복하고 해당 목록의 각 구성원을 변환하며 변환 된 구성원과 동일한 크기의 다른 목록을 리턴합니다 (예 : 문자열 목록을 대문자로 변환).
그들 사이의 중요한 차이점은 map
모든 결과를 컬렉션으로 모으고 foreach
아무것도 반환하지 않는다는 것입니다. map
함수를 사용하여 요소 컬렉션을 변환하려는 경우 일반적으로 사용되는 반면 foreach
각 요소에 대한 작업을 간단히 실행합니다.
간단히 말해서, foreach
요소 모음의 각 요소에 작업을 적용하기 map
위한 것이고, 하나의 모음을 다른 모음으로 변환하기위한 것입니다.
foreach
와 사이에는 두 가지 중요한 차이점이 있습니다 map
.
foreach
요소를 인수로 받아들이는 것 외에는 적용되는 조작에 대한 개념적 제한이 없습니다. 즉, 작업이 아무 것도 수행하지 않거나 부작용이 있거나 값을 반환하거나 값을 반환하지 않을 수 있습니다. 모든foreach
요소는 요소 컬렉션을 반복하고 각 요소에 작업을 적용하는 것입니다.map
반면에 작업에는 제한이 있습니다. 작업이 요소를 반환하고 요소를 인수로 받아 들일 것으로 예상합니다.map
동작이 각 요소에 대해 연산을 적용하고, 마지막으로 다른 콜렉션 동작의 각 호출의 결과를 저장 요소의 컬렉션을 통해 반복 할. 즉, 한 컬렉션을 다른 컬렉션으로map
변환 합니다.foreach
단일 요소 컬렉션과 함께 작동합니다. 이것은 입력 모음입니다.map
입력 콜렉션과 출력 콜렉션의 두 요소 콜렉션과 함께 작동합니다.
사실, 당신은 계층 적으로 두 가지를 볼 수 있습니다, 여기서이 두 알고리즘을 관련하는 실수하지 map
의 전문이다 foreach
. 즉, foreach
오퍼레이션을 사용 하여 인수를 변환하여 다른 콜렉션에 삽입 할 수 있습니다. 따라서 foreach
알고리즘은 알고리즘의 추상화, 일반화 map
입니다. 실제로 foreach
작동에 제한이 없기 때문에 foreach
가장 간단한 루핑 메커니즘이라고 할 수 있으며 루프가 수행 할 수있는 모든 작업을 수행 할 수 있습니다. map
보다 전문적인 다른 알고리즘뿐만 아니라 표현력도 있습니다. 한 컬렉션을 다른 컬렉션으로 매핑 (또는 변환)하려는 경우을 사용하는 map
것보다 사용하려는 경우 의도가 더 명확합니다 foreach
.
이 논의를 더 확장 copy
하고 컬렉션을 복제하는 루프 인 알고리즘을 고려할 수 있습니다 . 이 알고리즘 역시 알고리즘의 전문화입니다 foreach
. 요소가 지정된 경우 동일한 요소를 다른 컬렉션에 삽입하는 작업을 정의 할 수 있습니다. foreach
해당 작업에 사용 하는 경우 copy
명확성, 표현성 또는 명시 성이 떨어지더라도 사실상 알고리즘을 수행 한 것 입니다. 의는 더욱를 보자 : 우리는 말할 수 map
의 전문입니다 copy
, 자신의 전문화 foreach
. 반복되는 요소를 변경할map
수 있습니다 . 경우 map
는 단지 다음 요소 중 하나를 변경하지 않습니다 복사 요소 및 사용 사본을 의도를 더 명확하게 표현할 것입니다.
foreach
알고리즘 자체 또는 언어에 따라 반환 값이있을 수도 있고 없을 수도 있습니다. 예를 들어 C ++에서 foreach
원래받은 작업을 반환합니다. 아이디어는 오퍼레이션이 상태를 가질 수 있으며 해당 오퍼레이션이 요소에서 어떻게 진화했는지 점검하기 위해 해당 오퍼레이션을 다시 원할 수 있습니다. map
또한 값을 반환하거나 반환하지 않을 수 있습니다. C ++ transform
( map
여기에 해당)에서는 반복자를 출력 컨테이너 (컬렉션)의 끝으로 반환합니다. Ruby에서의 반환 값은 map
출력 시퀀스 (컬렉션)입니다. 따라서 알고리즘의 반환 값은 실제로 구현 세부 사항입니다. 그들의 효과는 그들이 돌아 오는 것일 수도 아닐 수도 있습니다.
Array.protototype.map
방법 및 Array.protototype.forEach
모두 매우 유사합니다.
다음 코드를 실행하십시오. http://labs.codecademy.com/bw1/6#:workspace
var arr = [1, 2, 3, 4, 5];
arr.map(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
});
console.log();
arr.forEach(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
});
정확한 결과를 제공합니다.
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
그러나 다음 코드를 실행할 때 비틀기가 발생합니다.
여기에서는 map 및 forEach 메소드의 반환 값 결과를 간단히 지정했습니다.
var arr = [1, 2, 3, 4, 5];
var ar1 = arr.map(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
return val;
});
console.log();
console.log(ar1);
console.log();
var ar2 = arr.forEach(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
return val;
});
console.log();
console.log(ar2);
console.log();
이제 결과는 까다 롭습니다!
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
[ 1, 2, 3, 4, 5 ]
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
undefined
결론
Array.prototype.map
배열을 반환하지만 Array.prototype.forEach
그렇지 않습니다. 따라서 map 메소드에 전달 된 콜백 함수 내에서 반환 된 배열을 조작 한 다음 반환 할 수 있습니다.
Array.prototype.forEach
주어진 배열을 통해서만 걸어서 배열을 걷는 동안 물건을 할 수 있습니다.
가장 '가시적 인'차이점은 맵이 결과를 새로운 컬렉션에 축적하는 반면 foreach는 실행 자체에 대해서만 수행된다는 것입니다.
but there are a couple of extra assumptions: since the 'purpose' of map is the new list of values, it doesn't really matters the order of execution. in fact, some execution environments generate parallel code, or even introduce some memoizing to avoid calling for repeated values, or lazyness, to avoid calling some at all.
foreach, on the other hand, is called specifically for the side effects; therefore the order is important, and usually can't be parallelised.
Short answer: map
and forEach
are different. Also, informally speaking, map
is a strict superset of forEach
.
Long answer: First, let's come up with one line descriptions of forEach
and map
:
forEach
iterates over all elements, calling the supplied function on each.map
iterates over all elements, calling the supplied function on each, and produces a transformed array by remembering the result of each function call.
In many languages, forEach
is often called just each
. The following discussion uses JavaScript only for reference. It could really be any other language.
Now, let's use each of these functions.
Using forEach
:
Task 1: Write a function printSquares
, which accepts an array of numbers arr
, and prints the square of each element in it.
Solution 1:
var printSquares = function (arr) {
arr.forEach(function (n) {
console.log(n * n);
});
};
Using map
:
Task 2: Write a function selfDot
, which accepts an array of numbers arr
, and returns an array wherein each element is the square of the corresponding element in arr
.
Aside: Here, in slang terms, we are trying to square the input array. Formally put, we are trying to compute it's dot product with itself.
Solution 2:
var selfDot = function (arr) {
return arr.map(function (n) {
return n * n;
});
};
How is map
a superset of forEach
?
You can use map
to solve both tasks, Task 1 and Task 2. However, you cannot use forEach
to solve the Task 2.
In Solution 1, if you simply replace forEach
by map
, the solution will still be valid. In Solution 2 however, replacing map
by forEach
will break your previously working solution.
Implementing forEach
in terms of map
:
Another way of realizing map
's superiority is to implement forEach
in terms of map
. As we are good programmers, we'll won't indulge in namespace pollution. We'll call our forEach
, just each
.
Array.prototype.each = function (func) {
this.map(func);
};
Now, if you don't like the prototype
nonsense, here you go:
var each = function (arr, func) {
arr.map(func); // Or map(arr, func);
};
So, umm.. Why's does forEach
even exist?
The answer is efficiency. If you are not interested in transforming an array into another array, why should you compute the transformed array? Only to dump it? Of course not! If you don't want a transformation, you shouldn't do a transformation.
So while map can be used to solve Task 1, it probably shouldn't. For each is the right candidate for that.
Original answer:
While I largely agree with @madlep 's answer, I'd like to point out that map()
is a strict super-set of forEach()
.
Yes, map()
is usually used to create a new array. However, it may also be used to change the current array.
Here's an example:
var a = [0, 1, 2, 3, 4], b = null;
b = a.map(function (x) { a[x] = 'What!!'; return x*x; });
console.log(b); // logs [0, 1, 4, 9, 16]
console.log(a); // logs ["What!!", "What!!", "What!!", "What!!", "What!!"]
In the above example, a
was conveniently set such that a[i] === i
for i < a.length
. Even so, it demonstrates the power of map()
.
Here's the official description of map()
. Note that map()
may even change the array on which it is called! Hail map()
.
Hope this helped.
Edited 10-Nov-2015: Added elaboration.
Here is an example in Scala using lists: map returns list, foreach returns nothing.
def map(f: Int ⇒ Int): List[Int]
def foreach(f: Int ⇒ Unit): Unit
So map returns the list resulting from applying the function f to each list element:
scala> val list = List(1, 2, 3)
list: List[Int] = List(1, 2, 3)
scala> list map (x => x * 2)
res0: List[Int] = List(2, 4, 6)
Foreach just applies f to each element:
scala> var sum = 0
sum: Int = 0
scala> list foreach (sum += _)
scala> sum
res2: Int = 6 // res1 is empty
If you're talking about Javascript in particular, the difference is that map
is a loop function while forEach
is an iterator.
Use map
when you want to apply an operation to each member of the list and get the results back as a new list, without affecting the original list.
Use forEach
when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want "side effects".
Other differences: forEach
returns nothing (since it is really a control flow function), and the passed-in function gets references to the index and the whole list, whereas map returns the new list and only passes in the current element.
ForEach tries to apply a function such as writing to db etc on each element of the RDD without returning anything back.
But the map()
applies some function over the elements of rdd and returns the rdd. So when you run the below method it won't fail at line3 but while collecting the rdd after applying foreach it will fail and throw an error which says
File "<stdin>", line 5, in <module>
AttributeError: 'NoneType' object has no attribute 'collect'
nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10])
num2 = nums.map(lambda x: x+2)
print ("num2",num2.collect())
num3 = nums.foreach(lambda x : x*x)
print ("num3",num3.collect())
참고URL : https://stackoverflow.com/questions/354909/is-there-a-difference-between-foreach-and-map
'Programing' 카테고리의 다른 글
Json Serialization에서 속성을 제외하는 방법 (0) | 2020.04.28 |
---|---|
phpmyadmin에서 기존 테이블에 대한 테이블 생성 스크립트를 생성하는 방법은 무엇입니까? (0) | 2020.04.28 |
우분투에서 postgresql을 완전히 제거하고 다시 설치하는 방법은 무엇입니까? (0) | 2020.04.28 |
Laravel 레코드가 있는지 확인 (0) | 2020.04.28 |
ID와 클래스의 차이점은 무엇입니까? (0) | 2020.04.28 |