使用javascript数组跳过take方法 [英] skip take methods with javascript arrays
问题描述
是否有方法可以跳过特定数量的对象并从javascript中的数组中获取一定数量的对象?
Are there methods by which I can skip a particular number of objects and take a certain number of objects from an array in javascript?
基本上我是模式寻找是这个。
Basically the pattern I'm looking for is this.
假设我有一个包含8个对象的数组。
Say I have an array of 8 objects.
第一个循环:
从数组返回索引0到3的对象。
Return objects at index 0 to 3 from the array.
第二个循环:
从数组返回索引4到7的对象。
return objects at index 4 to 7 from the array.
第三循环:
回到开头,所以再次返回0到3的对象。
Back to the beginning so return objects at 0 to 3 again.
广告infinitum .....
Ad infinitum.....
如果可能的话,我很想看到一个基于jquery的解决方案,但我也很开心,因为我渴望得到原始的javascript实现学习。
I'd love to see a jquery based solution if possible but I'm all open for raw javascript implementations too as I'm eager to learn.
干杯。
推荐答案
像这样的东西(纯JavaScript) ,不需要jQuery;)):
Something like this (plain JavaScript, no need for jQuery ;)):
var iterator = function(a, n) {
var current = 0,
l = a.length;
return function() {
end = current + n;
var part = a.slice(current,end);
current = end < l ? end : 0;
return part;
};
};
然后你可以打电话给它:
Then you can call it:
var next = iterator(arr, 3);
next(); // gives the first three
next(); // gives the next three.
//etc.
这种形式,最后一次迭代可能会返回更少的元素。你也可以扩展它并让函数接受一个变量步和一个不同的起始参数。
It this form, the last iteration might return less elements. You could also extend it and make the function accept a variable step and a different start parameter.
如果你想要环绕,就好像只剩下两个元素,从一开始就采用元素,然后它会变得更复杂;)
If you want to wrap around, like if there are only two elements left, to take elements from the beginning, then it gets a bit more sophisticated ;)
更新:包裹将是这样的:
var iterator = function(a, n) {
var current = 0,
l = a.length;
return function() {
end = current + n;
var part = a.slice(current,end);
if(end > l) {
end = end % l;
part = part.concat(a.slice(0, end));
}
current = end;
return part;
};
};
这篇关于使用javascript数组跳过take方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!