解析forEach运行原理

 
 
 1   var items = [ 1, 2, 3, 4, 5, 6 ];//普通数组
 2 var results = [];//空数组
 3 
 4 function async(arg, callback) {//两个参数arg表示下面传入的item索引值     callback表示async函数的回调函数
 5   console.log('参数为 ' + arg +' , 1秒后返回结果');
 6   setTimeout(function () { callback(arg * 2); }, 1000);
 7 }
 8 
 9 function final(value) {//普通函数 value表示接收results[results.length - 1]
10   console.log('完成: ', value);
11 }
12 
13 items.forEach(function(item) {  //表示items该数组遍历, item是该数组通过forEach遍历之后的索引值 在此循环内的代码将执行6次,
14   async(item, function(result){  //将item传入到async函数内被视为第一个参数,逗号后面的函数为async函数的第二个参数也就是回调函数callback,result此时也为arg(传入进来的值)
15     results.push(result);      //将results
16     if(results.length === items.length) {  //判断条件:如果results该数组的长度全等于items的长度
17       final(results[results.length - 1]);  //执行final函数,把results该数组的最后一次的值传入
18     }
19   })
20 });
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/52ljy/p/12742619.html