Javascript-如何在某些索引处启动forEach循环 [英] Javascript - how to start forEach loop at some index
问题描述
我有一个包含很多项目的数组,并且正在创建它们的列表.我当时想对列表进行分页.我想知道如何在数组中的某些index
处启动forEach
或for
循环,在我的示例中,这就是每个页面上列表中的项目数,因此我不需要进行迭代在每个循环的整个数组中?
I have an array with alot of items, and I am creating a list of them. I was thinking of paginating the list. I wonder how can I start a forEach
or for
loop at some index
in an array, that would be in my example the number of items in the list on each page, so that I don't need to iterate over the whole array in each loop?
arr.forEach(function (item) {
someFn(item);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
推荐答案
You could use a copy of the array, by using Array#slice
slice()
方法将数组的一部分的浅表副本返回到从头到尾选择的新数组对象中(不包括end).原始数组将不会被修改.
The
slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
array.slice(10, 20).forEach(someFn); // only for functions which respects API of forEach*
* 回调参数
或者您可以从给定的索引开始,到给定的索引结束.
Or you can start at a given index and end at a given index.
for (var i = 10, len = Math.min(20, arr.length); i < len; i++) {
someFn(arr[i]);
}
使用
Math.min(20, arr.length)
如果数组小于给定值20
,则
返回一个值.例如,如果数组只有索引0 ... 14,则结果为15.
returns a value, if the array is smaller than the given value 20
. For example if the array has only index 0 ... 14, you get as result 15.
这篇关于Javascript-如何在某些索引处启动forEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!