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

前端 未结 6 370
野的像风
野的像风 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:00

    Your example variable is called 'arr', but it's not an array at all (it's an object). This makes it a little confusing.

    When iterating over an object, there's no such thing as a "last" property, because the order of properties is undefined by design.

    When iterating over an array, you can simply compare the first parameter of the callback with the (array.length-1) to detect the last iteration.

    In code (for arrays):

    var arr = [ "a","b","c" ];
    
    $.each(arr, function(i,val) { if (i == arr.length-1) ... });
    

提交回复
热议问题