Home > Article > Web Front-end > How to use the foreach function in JavaScript
In How to use the foreach function in How to use the foreach function in How to use the foreach function in JavaScript, arrays can process multiple data, and the foreach function can perform similar processing on each data in the array. This article will introduce in detail the usage of the foreach function in How to use the foreach function in How to use the foreach function in How to use the foreach function in JavaScript.
Let’s first take a look at the basic syntax of the foreach function
The callback function is a process that is executed on each data of the array.
数组.foreach(回调函数)
We will use the foreach function for iterative processing below
The specific code is as follows
<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>How to use the foreach function in How to use the foreach function in How to use the foreach function in JavaScript</title> </head> <body> <script> var cats = [ '波斯猫', '橘猫', '蓝猫', '缅甸猫' ]; cats.forEach(function( cat ) { console.log( cat ); }); var runners = [ '张三', '李四', '王二', '陈五' ]; runners.forEach(function( runner, index ) { console.log("第" + (index + 1) + "是" + runner + "同学。" ); }); </script> </body> </html>
The running results are as follows
Let's analyze the above code in detail
Code 1:
var cats = [ '波斯猫', '橘猫', '蓝猫', '缅甸猫' ]; cats.forEach(function( cat ) { console.log( cat ); });
Set an array of "cats" and execute it on each array data foreach processing. The function receives each data in the array as a variable called cat and outputs it in console.log. Repeat this for the data in the array.
As a result, the following string is output.
Code 2:
var runners = [ '张三', '李四', '王二', '陈五' ]; runners.forEach(function( runner, index ) { console.log( (index + 1) + "第二位是" + runner + "同学。" ); });
The callback function can get the data index number as a parameter.
Set an array of "runners" and perform foreach processing on each array data.
As a result, the following string is output.
This article ends here. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to use the foreach function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!