Home > Web Front-end > JS Tutorial > Detailed explanation of the use of forEach and each in JavaScript

Detailed explanation of the use of forEach and each in JavaScript

黄舟
Release: 2017-07-27 16:27:16
Original
1353 people have browsed it

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);
Copy after login

is equivalent to:


var arr = [1, 2, 3, 4];
for (var k = 0, length = arr.length; k < length; k++) {
 alert(array[k]);
}
Copy after login

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
  });
Copy after login

is equivalent to:


  $.each([],function(index,value,array){

    //code something

  })
Copy after login

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
Copy after login

map: map means "mapping", the usage is similar to forEach, the usage is:


[].map(function(value,index,array){

  //code

})
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template