目前我有一个包含大约 20 条记录的数组,并且每个月增加 1 条记录。 (想想每月的时事通讯)。我不想循环遍历每一个,而是想循环遍历前 10 个或 15 个。
$.each(newArray, function (index, item) {
$('#CommunityNL ul').append("<li>" + "<a href='" + item.FileRef + "'>" + item.Title + "</a>" + "</li>");
count++;
});
我找到了 splice 方法,它通过在循环之前拼接 newArray 来完美地工作,这样 newArray 中只有 10 个项目。我不确定这是否是最好的做事方式?
最佳答案
来自docs :
We can break the
$.each()
loop at a particular iteration by making the callback function return false. Returning non-false
is the same as acontinue
statement in a for loop; it will skip immediately to the next iteration.
所以你可以使用类似的东西
$.each(array, function(index, item) {
if (index == endIndex) return false;
// Do things
});
或者只是使用普通循环。为什么还需要 jQuery 来迭代数组?
for (var i=0, to=Math.min(array.length, endIndex); i < to; ++i) {
// Do things with array[i]
}
关于javascript - 如何让数组循环 x 次而不是每个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40795446/