foreach is the most basic of the new array method in ECMA5, that is, traversal, loop. For example, the following example:
[1, 2, 3, 4].foreach (alert);
is equivalent to the following for loop
1 var array = [1, 2, 3, 4]; 2 for (var k = 0, length = array.length; k < length; k++) {3 alert (array[k]); 4 }
Array in ES5 new method, the parameters are function type, the default is the parameter, the function callback in the Foreach method supports 3 parameters, the 1th is the array content of the traversal, the 2nd is the corresponding array index, and 3rd is the array itself.
Therefore, we have:
[].foreach (function (value, index, array) { //...});
Compare the $.each methods in jquery:
$.each ([], function (index, value, array) { //...});
Will find that the 1th and 2nd parameters are exactly the opposite, we have to pay attention to, do not remember the wrong. Similar to the following methods, such as $.map.
var data=[1,3,4]; var sum=0;d Ata.foreach (function (Val,index,arr) { console.log (arr[index]==val); ==> true sum+=val }) console.log (sum); ==> 8
Map
The map here is not meant by "maps", but refers to "maps". [].map (); The basic usage is similar to the Foreach method:
Array.map (callback,[thisobject]);
The parameters of the callback are similar:
[].map (function (value, index, array) { //...});
The role of the map method is not difficult to understand, "mapping", that is, the original array is "mapped" into a corresponding new array. The following example is the value of the square:
var data=[1,3,4] Var squares=data.map (function (Val,index,arr) { console.log (arr[index]==val); ==> true return Val*val }) Console.log (squares); ==> [1, 9, 16]
Note: Since the foreach and map are ECMA5 additions to the array, the browsers below IE9 are not supported (ie is evil), but can be extended from the array prototype to achieve all of the above functions, such as the Foreach method:
if (typeof Array.prototype.forEach! = "function") { Array.prototype.forEach = function () {/ * implementation */ };}
Citation to: http://www.jb51.net/article/81955.htm
The foreach, $.each, and map methods in JS