foreach is a method of manipulating an array in ES5, and the main function is to iterate through the array, for example:
12 |
var arr = [1,2,3,4]; arr.forEach(alert); |
Equivalent to:
1234 |
var arr = [1, 2, 3, 4]; for ( var k = 0, length = arr.length; k < length; k++) { alert(array[k]); } |
The function callback in the Foreach method has three parameters: the first argument is the array contents of the traversal, the second parameter is the corresponding array index, and the third parameter is the array itself
So:
[].foreach (function (Value,index,array) {
Code something
});
Equivalent to:
$.each ([],function (Index,value,array) {
Code something
})
Write an example;
123456 |
var arr = [1,2,3,4]; arr.forEach( function (value,index,array){ array[index] == value; //结果为true sum+=value; }); console.log(sum); //结果为 8 |
Map:map is a "map" that uses the same meaning as a forEach, using the following:
[].map (function (Value,index,array) {
Code
})
On the foreach and each in JavaScript