foreach is the most basic one of the new array methods in ECMA5, that is, traversal, loop. For example, the following example:
[1, 2, 3, 4].foreach (alert);
Equivalent to the following for loop
var array = [1, 2, 3, 4];
for (var k = 0, length = array.length k < length; k++) {
alert (array[k]);
}
Array in ES5 's new method, the parameters are function types, the default is the argument, the function callback in the Foreach method supports 3 parameters, the 1th is the array content that is traversed, the 2nd is the corresponding array index, and the 3rd is the array itself.
Therefore, we have:
[].foreach (function (value, index, array) {
//...
});
Compare the $.each method in jquery:
$.each ([], function (index, value, array) {
//...
});
Will find that the 1th and 2nd parameters are exactly the opposite, we should pay attention to, do not remember wrong. The following similar methods, such as $.map, are also true.
var data=[1,3,4];
var sum=0;
Data.foreach (function (Val,index,arr) {
console.log (arr[index]==val); ==> true
sum+=val
})
console.log (sum); ==> 8
Map
The map here is not the meaning of "maps", but the "mapping". [].map (); The basic usage is similar to the Foreach method:
Array.map (callback,[thisobject]);
The callback parameters 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" to the corresponding new array. The following example is a numerical sum:
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 both foreach and map are ECMA5 additions to the array, the browsers below IE9 are not supported (evil IE AH), but you can expand from the array prototype to achieve all of these functions, such as the Foreach method:
if (typeof Array.prototype.forEach!= "function") {
Array.prototype.forEach = function () {/
* implementation/
}
;}
The above JS in the foreach, $.each, map method recommended is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.