Let's first look at the similarities between the two.
var arr = [' A ', ' B ', ' C ', ' d '];arr.foreach (Item,index,arr) {//item represents each item in the array, index identifies the subscript for the current item, Arr represents the current array console.log (item); Console.log (index); Console.log (arr); Console.log (this);},123); Here the 123 parameter, which represents the function of this point, can be written without writing, if not written, then this point windowarr.map (function (Item,index,arr) { //parameter meaning the same as foreach Console.log (item); Console.log (index); Console.log (arr); Console.log (this);},123);
After running, you can see that there is no difference between the two parameters, in addition to the two there is a feature, is not to stop the inside of the traversal, unless the program error, then the difference between the two there???
is the return value!!!
var a = Arr.foreach (function(item,index,arr) { return 123}); var b = Arr.map (function(item,index,arr) { return 123}); Console.log ( a); // undefinedconsole.log (b); // [123,123,123,123]
What can we do with this feature of map, like
var b = Arr.map (function(item,index,arr) { return item+ ' a ';}); Console.log (b); ["AA", "BA", "Ca", "Da"]
foreach is the method introduced in Es3, and map is a method introduced in ES5, and there are still some compatibility issues in the low version of IE.
The difference between a foreach and a map in JS