developer tip

자바 스크립트 forEach 메소드는 어떤 용도로 사용됩니까 (그 맵은 할 수 없음)?

copycodes 2020. 9. 7. 08:21
반응형

자바 스크립트 forEach 메소드는 어떤 용도로 사용됩니까 (그 맵은 할 수 없음)?


내가 map과 foreach에서 보는 유일한 차이점 map은 배열을 반환하고 forEach그렇지 않다는 것입니다. 그러나 forEach" func.call(scope, this[i], i, this);" 메서드 의 마지막 줄도 이해하지 못합니다 . 예를 들어, "없는 this"및 " scope"동일한 개체 참조되지 않고 this[i]i루프의 현재 값을 참조?

다른 게시물에서 누군가 " forEach목록의 각 요소를 기반으로 무언가를하고 싶을 때 사용 합니다. 예를 들어 페이지에 항목을 추가 할 수 있습니다. 기본적으로"부작용 "을 원할 때 유용합니다. 부작용이 무엇을 의미하는지 모르겠습니다.

Array.prototype.map = function(fnc) {
    var a = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
        a[i] = fnc(this[i]);
    }
    return a;
}

Array.prototype.forEach = function(func, scope) { 
    scope = scope || this; 
    for (var i = 0, l = this.length; i < l; i++) {
        func.call(scope, this[i], i, this); 
    } 
}

마지막으로, 다음과 같이 숫자를 조작하는 것 외에 자바 스크립트에서 이러한 메서드를 실제로 사용하는 방법이 있습니까 (데이터베이스를 업데이트하지 않기 때문에) :

alert([1,2,3,4].map(function(x){ return x + 1})); //this is the only example I ever see of map in javascript.

답장을 보내 주셔서 감사합니다.


예제에서 map의 근본적인 차이점 은 원래 배열 요소에서 작동하는 반면 명시 적으로 새 배열을 결과로 반환한다는 것입니다.forEachforEachmap

forEach변화하는 선택적하고 - - 각 요소를 원래의 배열에 당신이 몇 가지 조치를 취하고있다. forEach메서드는 각 요소에 대해 제공 한 함수를 실행하지만 아무것도 반환하지 않습니다 ( undefined). 반면에 map배열을 살펴보고 각 요소에 함수를 적용한 다음 결과를 새 배열로 내 보냅니다 .

"부작용" forEach은 원래 배열이 변경된다는 것입니다. "부작용 없음" map은 관용적 사용법에서 원래 배열 요소가 변경 되지 않음을 의미합니다 . 새 배열은 원래 배열의 각 요소에 대한 일대일 매핑입니다. 매핑 변환은 제공된 함수입니다.

관련된 데이터베이스가 없다는 사실은 결국 어떤 언어로든 프로그래밍의 본질 중 하나 인 데이터 구조에 대해 작업 할 필요가 없다는 것을 의미하지는 않습니다. 마지막 질문에 관해서는 배열에 숫자뿐만 아니라 객체, 문자열, 함수 등이 포함될 수 있습니다.


두 가지 방법 사이의 주요 차이점은 개념 및 문체입니다 : 당신이 사용하는 forEach당신이 뭔가를 할 때 배열의 각 요소 ( "와"하고는 "부작용"을 의미 인용 포스트, 내가 무슨 생각입니다) , 반면 배열의 각 요소 map복사하고 변환 하려는 경우 (원본을 변경하지 않고) 사용합니다.

둘 다 mapforEach배열의 각 항목에 대해 함수를 호출하고 해당 함수가 사용자 정의되어 있기 때문에 하나를 사용하여 수행 할 수있는 작업이 거의 없습니다. 추악하지만 map배열을 제자리에서 수정하거나 배열 요소로 무언가를 수행하는 데 사용할 수 있습니다.

var a = [{ val: 1 }, { val: 2 }, { val: 3 }];
a.map(function(el) {
    el.val++; // modify element in-place
    alert(el.val); // do something with each element
});
// a now contains [{ val: 2 }, { val: 3 }, { val: 4 }]

그러나 사용하려는 의도는 훨씬 명확하고 분명합니다 forEach.

var a = [{ val: 1 }, { val: 2 }, { val: 3 }];
a.forEach(function(el) { 
    el.val++;
    alert(el.val);
});

Especially if, as is usually the case in the real world, el is a usefully human-readable variable:

cats.forEach(function(cat) { 
    cat.meow(); // nicer than cats[x].meow()
});

In the same way, you can easily use forEach to make a new array:

var a = [1,2,3],
    b = [];
a.forEach(function(el) { 
    b.push(el+1); 
});
// b is now [2,3,4], a is unchanged

but it's cleaner to use map:

var a = [1,2,3],
    b = a.map(function(el) { 
        return el+1; 
    });

Note as well that, because map makes a new array, it likely incurs at least some performance/memory hit when all you need is iteration, particularly for large arrays - see http://jsperf.com/map-foreach

As for why you'd want to use these functions, they're helpful any time you need to do array manipulation in javascript, which (even if we're just talking about javascript in a browser environment) is pretty often, almost any time you're accessing an array that you're not writing down by hand in your code. You might be dealing with an array of DOM elements on the page, or data pulled from an AJAX request, or data entered in a form by the user. One common example I run into is pulling data from an external API, where you might want to use map to transform the data into the format you want and then use forEach to iterate over your new array in order to display it to your user.


The voted answer (from Ken Redler) is misleading.

A side effect in computer science means that a property of a function/method alters a global state [wiki]. In some narrow sense, this may also include reading from a global state, rather than from arguments. In imperative or OO programing, side effects appear most of the time. And you are probably making use of it without realizing.

The significiant difference between forEach and map is that map allocates memory and stores the returning value, while forEach throws it away. See emca spec for more information.

As for the reason why people say forEach is used when you want a side effect is that the return value of forEach is always undefined. If it has no side effect (does not change global state), then the function is just wasting cpu time. An optimizing compiler will eliminate this code block and replace the it with the final value (undefined).

By the way, it should be noted that JavaScript has no restriction on side effects. You can still modify the original array inside map.

var a = [1,2,3]; //original
var b = a.map( function(x,i){a[i] = 2*x; return x+1} );
console.log("modified=%j\nnew array=%j",a,b);
// output:
// modified=[2,4,6]
// new array=[2,3,4]

This is a beautiful question with an unexpected answer.

The following is based on the official description of Array.prototype.map().

There is nothing that forEach() can do that map() cannot. That is, map() is a strict super-set of forEach().

Although map() is usually used to create a new array, it may also be used to change the current array. The following example illustrates this:

var a = [0, 1, 2, 3, 4], mapped = null;
mapped = a.map(function (x) { a[x] = x*x*x; return x*x; });
console.log(mapped); // logs [0, 1, 4, 9, 16]  As expected, these are squares.
console.log(a); // logs [0, 1, 8, 27, 64] These are cubes of the original array!!

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(), and in particular its ability to change the array on which it is called.

Note1:
The official description implies that map() may even change length the array on which it is called! However, I cannot see (a good) reason to do this.

Note2:
While map() map is a super-set of forEach(), forEach() should still be used where one desires the change a given array. This makes your intentions clear.

Hope this helped.


You can use map as though it were forEach.

It will do more than it has to, however.

scope can be an arbitrary object; it's by no means necessarily this.

As for whether there are real uses for map and forEach, as well to ask if there are real uses for for or while loops.


While all the previous questions are correct, I would definitely make a different distinction. The use of map and forEach can imply intent.

I like to use map when I am simply transforming the existing data in some way (but want to make sure the original data is unchanged.

I like to use forEach when I am modifying the collection in place.

For instance,

var b = [{ val: 1 }, { val: 2 }, { val: 3 }];
var c = b.map(function(el) {
    return { val: el.val + 1 }; // modify element in-place
});
console.log(b);
//  [{ val: 1 }, { val: 2 }, { val: 3 }]
console.log(c);
//  [{ val: 3 }, { val: 4 }, { val: 5 }]

My rule of thumb being making sure when you map you are always creating some new object/value to return for each element of the source list and returning it rather than just performing some operation on each element.

Unless you have any real need to modify the existing list, it doesn't really make sense to modify it in place, and fits better into functional/immutable programming styles.


Once again, I feel like a necromancer adding a response to a question that has been asked 5 years ago (happily there is rather recent activity, so I am not the only one disturbing the dead:).

Others have already posted about your main question regarding the difference between the functions. But for...

are there any real uses for these methods in javascript (since we aren't updating a database) other than to manipulate numbers like this:

...it's funny you should ask. Just today I wrote a piece of code that assigns a number of values from a regular expression to multiple variables using map for transformation. It was used to convert a very complicated text based structure into visualizeable data ... but for simplicity's sake, I shall offer an example using date strings, because those are probably more familiar for everyone (though, if my problem had actually been with dates, instead of map I would've used Date-object, which would've done the job splendidly on its own).

const DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/;
const TEST_STRING = '2016-01-04T03:20:00.000Z';

var [
    iYear,
    iMonth,
    iDay,
    iHour,
    iMinute,
    iSecond,
    iMillisecond
    ] = DATE_REGEXP
        // We take our regular expression and...
        .exec(TEST_STRING)
        // ...execute it against our string (resulting in an array of matches)...
        .slice(1)
        // ...drop the 0th element from those (which is the "full string match")...
        .map(value => parseInt(value, 10));
        // ...and map the rest of the values to integers...

// ...which we now have as individual variables at our perusal
console.debug('RESULT =>', iYear, iMonth, iDay, iHour, iMinute, iSecond, iMillisecond);

So ... while this was just an example - and only did a very basic transformation for the data (just for sake of example) ... having done this without map would've been a much more tedious task.

Granted, it is written in a version of JavaScript that I don't think too many browsers support yet (at least fully) but - we're getting there. If I needed to run it in browser, I believe it would transpile nicely.


TL;DR answer --

map always returns another array.

forEach does not. It is up to you to decide what it does. Return an array if you want or do something else if you don't.

Flexibility is desirable is certain situations. If it isn't for what you are dealing with then use map.

참고URL : https://stackoverflow.com/questions/3034392/what-use-does-the-javascript-foreach-method-have-that-map-cant-do

반응형