catch forEach最后一次迭代 [英] catch forEach last iteration

查看:85
本文介绍了catch forEach最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});

循环结束时如何捕捉?我可以如果(i == 3)但我可能不知道我的数字是多少。

How to catch when the loop ending? I can do if(i == 3) but I might don't know what is the number of my array.

推荐答案

ES6 +的更新答案是此处

Updated answer for ES6+ is here.

arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

将输出:

Last callback call at index 2 with value 3

这种方式的工作原理是测试 arr.length 对阵列的当前索引,传递给回调函数

The way this works is testing arr.length against the current index of the array, passed to the callback function.

这篇关于catch forEach最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆