跳过使用 javascript 数组的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5463443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:17:20  来源:igfitidea点击:

skip take methods with javascript arrays

javascriptjquery

提问by James South

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?

是否有方法可以跳过特定数量的对象并从 javascript 中的数组中获取一定数量的对象?

Basically the pattern I'm looking for is this.

基本上我正在寻找的模式是这样的。

Say I have an array of 8 objects.

假设我有一个包含 8 个对象的数组。

First loop:

第一个循环:

Return objects at index 0 to 3 from the array.

从数组中返回索引 0 到 3 处的对象。

Second loop:

第二个循环:

return objects at index 4 to 7 from the array.

从数组中返回索引 4 到 7 处的对象。

Third loop:

第三个循环

Back to the beginning so return objects at 0 to 3 again.

回到开头,再次返回 0 到 3 处的对象。

Ad infinitum.....

无止境……

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.

如果可能的话,我很想看到一个基于 jquery 的解决方案,但我也对原始 javascript 实现持开放态度,因为我渴望学习。

Cheers.

干杯。

回答by Felix Kling

Something like this (plain JavaScript, no need for jQuery ;)):

像这样的东西(纯 JavaScript,不需要 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.

DEMO

演示

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 ;)

如果你想环绕,就像只剩下两个元素一样,从一开始就获取元素,那么它会变得更复杂;)

Update:Wrap around would be something like this:

更新:环绕将是这样的:

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;
    };
};

DEMO

演示

回答by Brad Christie

I think you want Array.sliceor Array.splice.

我想你想要Array.sliceArray.splice

var ary = [0,1,2,3,4,5,6,7];
alert(ary.splice(0,3).join(','));

回答by Mike Park

回答by Stefan Kendall

If you have a jQuery reference, jQuery has a slice method too.

如果您有 jQuery 参考,jQuery 也有切片方法