catch forEach last iteration

前端 未结 3 1011
情话喂你
情话喂你 2021-01-31 00:55
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 kn

3条回答
  •  忘掉有多难
    2021-01-31 01:25

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

    would output:

    Last callback call at index 2 with value 3
    

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

提交回复
热议问题