Javascript - how to start forEach loop at some index

前端 未结 6 1615
予麋鹿
予麋鹿 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 01:11

    You could apply some kind of implementation of the iterator pattern.

    var Iterator = function (list, position) {
      return {
        isNext: function () {
          return position + 1 < list.length;
        },
        isDefined: function () {
          return (position < list.length && position >= 0);
        },
        element: function () {
          return list[position];
        },
        position: function () {
          return position;
        },
        moveNext: function () {
          if (this.isNext()) { return Iterator(list, position + 1); }
          return Iterator([], 0);
        }      
    }
    
    Iterator.forEach = function (action, iterator, length) {
      var counter = 0;
      while (counter < length && iterator.isDefined()) {
        counter = counter + 1;
        action(iterator.element(), iterator.position());
        iterator = iterator.moveNext();
      }
    
      return iterator;
    }   
    

    And then have an iterator to use for going over the list and keep the state of the last iteration over a list.

    var list = [1, 3, 5, 3, 6];
    var iterator = Iterator(list, 0);
    
    iterator = Iterator.forEach(function (element, index) {
      console.log(element, index);
    }, iterator, 3);
    
    //1 0
    //3 1
    //5 2
    
    Iterator.forEach(function (element, index) {
       console.log(element, index);              
    }, iterator, 5);
    
    //3 3
    //6 4
    

提交回复
热议问题