Home > Web Front-end > JS Tutorial > body text

A brief introduction to foreach and each in JS

黄舟
Release: 2017-11-16 14:56:08
Original
5047 people have browsed it

In the previous article, we introduced the detailed explanation of the foreach statement in JS. I believe that everyone has a certain degree of familiarity and understanding of the use of the foreach statement, so today we will continue to introduce JS to you. Foreach and each

forEach is a method of operating array in ES5. The 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);    //结果为 10
Copy after login

map: map means "mapping". Usage and forEach is similar, the usage is:

[].map(function(value,index,array){
  //code
})
Copy after login

Summary:

This article introduces in detail the introduction of foreach and each in JS, do you believe it? I have a deep understanding and understanding of this, I hope it will be helpful to your work!

Related recommendations:

Detailed explanation of Foreach syntax in JavaScript


javascript forEach() method explanation


javascript forEach Function implementation code

The above is the detailed content of A brief introduction to foreach and each in JS. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!