Paginate Javascript array

前端 未结 7 1836
庸人自扰
庸人自扰 2020-12-02 08:55

I am trying to write a Javascript function that takes an array, page_size and page_number as parameters and returns an array that mimi

7条回答
  •  春和景丽
    2020-12-02 09:52

    You can use Array.prototype.slice and just supply the params for (start, end).

    function paginate(array, page_size, page_number) {
      // human-readable page numbers usually start with 1, so we reduce 1 in the first argument
      return array.slice((page_number - 1) * page_size, page_number * page_size);
    }
    
    console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));
    console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));

提交回复
热议问题