Javascript catch forEach 最后一次迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29738535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:53:15  来源:igfitidea点击:

catch forEach last iteration

javascriptjquery

提问by Jamie Anderson

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

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.

循环结束时如何捕捉?我可以做,if(i == 3)但我可能不知道我的阵列的数量是多少。

回答by jdphenix

Updated answer for ES6+ is here.

ES6+ 的更新答案在这里



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

would output:

会输出:

Last callback call at index 2 with value 3

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

其工作方式是arr.length针对传递给回调函数的数组的当前索引进行测试。

回答by Sterling Bourne

The 2018 ES6+ ANSWER IS:

2018 ES6+ 答案是

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

回答by Justin Coleman

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})