如何找出jQuery中每个()的最后一个索引?

daG*_*vis 39 indexing each jquery loops

我有这样的事......

$( 'ul li' ).each( function( index ) {

  $( this ).append( ',' );

} );
Run Code Online (Sandbox Code Playgroud)

我需要知道最后一个元素的索引是什么,所以我可以这样做......

if ( index !== lastIndex ) {

  $( this ).append( ',' );

} else {

  $( this ).append( ';' );

}
Run Code Online (Sandbox Code Playgroud)

伙计们,有什么想法?

Luk*_*ger 82

var total = $('ul li').length;
$('ul li').each(function(index) {
    if (index === total - 1) {
        // this is the last one
    }
});
Run Code Online (Sandbox Code Playgroud)

  • +这是一个很好的例子,但是当使用命名的`keys`(`indices`)循环JSON对象时,这不起作用,因为`index`不是数字. (3认同)

BnW*_*BnW 14

var arr = $('.someClass');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Run Code Online (Sandbox Code Playgroud)


Ray*_*nos 9

记得缓存选择器$("ul li")因为它不便宜.

缓存长度本身是一个微优化,但这是可选的.

var lis = $("ul li"),
    len = lis.length;

lis.each(function(i) {
    if (i === len - 1) {
        $(this).append(";");
    } else {
        $(this).append(",");
    }
});
Run Code Online (Sandbox Code Playgroud)


Mut*_*utt 6

    var length = $( 'ul li' ).length
    $( 'ul li' ).each( function( index ) {
        if(index !== (length -1 ))
          $( this ).append( ',' );
        else
          $( this ).append( ';' );

    } );
Run Code Online (Sandbox Code Playgroud)