2

I am using the $.each() method of jQuery to loop over a couple of objects. Is there a way to find out if there are more objects to come in the $.each() method?

Something like:

$.each(data, function(o, myObject) {
    if(data.hasMoreObjects) {
        // append something 
    } else {
        // append nothing
    }
});
4

5 回答 5

4

传递给回调函数的第一个参数是index. 您可以将其与 进行比较length以确定是否有更多元素。

$.each(data, function(index, myObject) {
    if (index === (data.length - 1)) {
        // this is the last
    } else {
        // there are more coming
    }
});

根据data具体情况,您可能需要使用其他一些属性来代替data.length. 例如,如果data是一个对象,您将使用Object.keys(data).length,

$.each文档和 Object.keys的文档。

于 2013-01-07T17:57:52.827 回答
3

反过来会更容易。例如,如果您有:

a b c d

你想|在它们之间插入,你可以这样做:

a| b| c| d

换句话说,通过循环并将 a 添加|到除最后一个之外的所有内容。但是对于第一个来说,以不同的方式工作会更容易:

a |b |c |d

因为你可以这样做:

var isfirst = true;
$.each(data, function(o, myObject) {
    if( isfirst) {
        isfirst = false;
    }
    else {
        // do something
    }
});

但是,如果这是不可能的,您可能必须循环一次来计算元素(除非它是一个数组而不是一个对象,在这种情况下.length会很好),然后将一个迭代器添加到您的循环中。

于 2013-01-07T17:58:01.267 回答
3

所有其他答案似乎都假设它data是一个Array(或具有某些属性.length),但根据jQuery 页面,您可以$.each在任何Object上使用。

这是一种获取对象的最后一个可枚举键的方法

function lastKey(o) {
    var keys = Object.keys(o);
    return keys[keys.length-1];
}

然后,您可以在$.each.

于 2013-01-07T18:04:39.427 回答
1
var howmany = data.length,
    i = 1;
$.each(data, function(o, myObject) {
    if(i == howmany) {
        // do something with the last
    }
    else {
        // do something with the others
    }
    i++;
}
于 2013-01-07T17:58:38.693 回答
1

将索引与长度 od 数据对象进行比较,

尝试这个

$.each(data, function(index, myObject) {
 if (index === (data.length - 1)) {
    //append nothing     } else {
    // append something
 }
});
于 2013-01-07T18:01:47.273 回答