Home  >  Article  >  Web Front-end  >  A brief introduction to foreach and each in JS

A brief introduction to foreach and each in JS

黄舟
黄舟Original
2017-11-16 14:56:085063browse

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);

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);    //结果为 10

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

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

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!

Statement:
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