How to catch last iteration inside $.each in jQuery?

前端 未结 6 458
野的像风
野的像风 2021-01-03 22:58
var arr = {\'a\':fn1,\'b\':fn2,\'c\':fn3}

$.each(arr,function(name,func){
(do something particular for the last iteration)
...
})

It\'ll be best i

6条回答
  •  既然无缘
    2021-01-03 23:06

    Here I propose a brand new, improved answer.

    An elegant way could be using a after() function wrapper. Here's the code:

    function after(fn, times){
       return function(){
         if(--times === 0){
           var args = Array.prototype.slice.call(arguments);
           fn.apply(this, args);
         }
       };
     }
    

    fn is the function you want to be executed at last, times is the number of different response you are waiting for.

    after() wraps your function and creates a new function that runs its code only after times calls. Here's an example in brief:

    function onLastResponse(foo){
      console.log('this is last iteration');
    }
    
    var myCallback = after(onLastResponse, 3);
    
    myCallback(); //not executed
    myCallback(); //not executed
    myCallback(); //executed
    

    Check this jsbin for a live example: https://jsbin.com/sufaqowumo/edit?js,console

提交回复
热议问题