Javascript - how to start forEach loop at some index

前端 未结 6 1616
予麋鹿
予麋鹿 2021-01-04 00:31

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

6条回答
  •  感情败类
    2021-01-04 00:58

    You could use a copy of the array, by using Array#slice

    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*
    

    * parameters for a callback

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

    With

    Math.min(20, arr.length)
    

    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.

提交回复
热议问题