js参考---forEach

js参考---forEach

一、总结

一句话总结:

forEach()方法需要一个回调函数作为参数,这个回调函数会被浏览器传进去三个参数,分别是value(值)、index(索引)、arr(数组),例如 arr.forEach(function(value , index , obj){});
arr.forEach(function(value , index , obj){
  console.log(value);
});

1、回调函数是什么?

由我们创建但是不由我们调用的函数,我们称为回调函数,例如 arr.forEach(function(value , index , obj){});
arr.forEach(function(value , index , obj){
  console.log(value);
});

二、forEach

博客对应课程的视频位置:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <script type="text/javascript">
 7             
 8             /*
 9              * 一般我们都是使用for循环去遍历数组,
10              *     JS中还为我们提供了一个方法,用来遍历数组
11              * forEach()
12              *         - 这个方法只支持IE8以上的浏览器
13              *             IE8及以下的浏览器均不支持该方法,所以如果需要兼容IE8,则不要使用forEach
14              *             还是使用for循环来遍历
15              */
16             
17             //创建一个数组
18             var arr = ["孙悟空","猪八戒","沙和尚","唐僧","白骨精"];
19             
20             /*
21              * forEach()方法需要一个函数作为参数
22              *     - 像这种函数,由我们创建但是不由我们调用的,我们称为回调函数
23              *     - 数组中有几个元素函数就会执行几次,每次执行时,浏览器会将遍历到的元素
24              *         以实参的形式传递进来,我们可以来定义形参,来读取这些内容
25              *     - 浏览器会在回调函数中传递三个参数:
26              *         第一个参数,就是当前正在遍历的元素
27              *         第二个参数,就是当前正在遍历的元素的索引
28              *         第三个参数,就是正在遍历的数组
29              *         
30              */
31             arr.forEach(function(value , index , obj){
32                 console.log(value);
33             });
34             
35             
36         </script>
37     </head>
38     <body>
39     </body>
40 </html>
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/12501699.html