catch forEach last iteration

前端 未结 3 948
情话喂你
情话喂你 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:19

    The 2018 ES6+ ANSWER IS:

        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}` ); 
          }
        });
    
    0 讨论(0)
  • 2021-01-31 01:20
    const arr= [1, 2, 3]
    arr.forEach(function(element){
     if(arr[arr.length-1] === element){
      console.log("Last Element")
     }
    })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题