Home > Article > Web Front-end > Detailed explanation of the use of forEach and each in JavaScript
This article mainly introduces you to the relevant information about the use of forEach and each in JavaScript. The article introduces it in detail through the example code, which has certain reference and learning value for everyone. Friends who need it can follow the editor below. Get up and study.
This article mainly introduces to you the relevant content about forEach and each in JavaScript, and shares it for your reference and study. Without further ado, let’s take a look at the detailed introduction:
forEach It is a method of operating arrays in ES5. Its main function is to traverse the array. For example:
var arr = [1,2,3,4]; arr.forEach(alert);
is equivalent to:
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 parameter is the traversed array content, the second parameter is the corresponding array index, and the third parameter is the array itself
Therefore:
[].forEach(function(value,index,array){ //code something });
is equivalent to:
$.each([],function(index,value,array){ //code something })
Write an example;
var arr = [1,2,3,4]; arr.forEach(function(value,index,array){ array[index] == value; //结果为true sum+=value; }); console.log(sum); //结果为 8
map: map means "mapping", the usage is similar to forEach, the usage is:
[].map(function(value,index,array){ //code })
Summary
The above is the detailed content of Detailed explanation of the use of forEach and each in JavaScript. For more information, please follow other related articles on the PHP Chinese website!