如何将数组划分为具有灵活输出长度的块?

How to divide an array to chunks with flexible output length?

如何将数组分割成输出长度灵活的块?
渲染分页是必要的,我们的元素空间有限,
如果我们有几页元素——我们需要用数组 (prev/next) 代替 el 来显示按钮。

示例f()输入输出,当第一个参数是带有数据的数组时,
第二个参数是列表中元素的最大值,包括导航按钮:

      f([1,2,3,4], 4) => [1,2,3,4]
    f([1,2,3,4,5], 4) => [[1,2,3], [4,5]]
  f([1,2,3,4,5,6], 4) => [[1,2,3], [4,5,6]]
f([1,2,3,4,5,6,7], 4) => [[1,2,3], [4,5], [6,7]]
f([7,6,5,4,3,2,1], 4) => [[7,6,5], [4,3], [2,1]]
f([1,2,3,4,5,6,7], 6) => [[1,2,3,4,5], [6,7]]


最多 6 个元素的设计布局示例

第 1 页:

第 2 页:

最后一页:

我希望这会奏效!

a=[1,2,3,4,5,6,7,8,9,2];
result=[];
start = true;
function f(arr,n){
    if(arr.length >= n-2){
        console.log(start)
        if(start){
            start=false;
            result.push(arr.splice(0,n-1))
            return f(arr,n)
        }else{
            result.push(arr.splice(0,n-2))
            return f(arr,n)
        }
    } else {
        result.push(arr);
        return 1;
    }
}
f(a,6);
console.log(result)

首先,确定 page/two 页是否足够。如果不是,循环数组。

let f = (array, max) => {
  if (array.length / max <= 1)
    return array

  if (array.length / (max - 1) <= 2)
    return [array.slice(0, max - 1), array.slice(max - 1, array.length)]

  let result = []
  let n = 0
  while (n <= array.length - 1) {
    if (n == 0) {
      result.push(array.slice(n, n + max - 1))
      n += max - 1
    } else {
      let pushAmount = n+max-1 >= array.length ? max-1 : max-2
      result.push(array.slice(n, n + pushAmount))
      n += pushAmount
    }
  }

  return result
}

console.log(f([1, 2, 3, 4], 4))
console.log(f([1, 2, 3, 4, 5], 4))
console.log(f([1, 2, 3, 4, 5, 6], 4))
console.log(f([1, 2, 3, 4, 5, 6, 7], 4))
console.log(f([7, 6, 5, 4, 3, 2, 1], 4))
console.log(f([1, 2, 3, 4, 5, 6, 7], 6))

另一种解决方案 - 使用递归。我觉得这样更容易理解。

f = (arr, max, first = true) => {
  if (arr.length == 0) return []
  const last = arr.length <= max - !first
  const curLen = max - !first - !last
  const cur = arr.slice(0, curLen)
  const next = f(arr.slice(curLen), max, false)
  return [cur, ...next]
}


console.log(f([1, 2, 3, 4], 4))
console.log(f([1, 2, 3, 4, 5], 4))
console.log(f([1, 2, 3, 4, 5, 6], 4))
console.log(f([1, 2, 3, 4, 5, 6, 7], 4))
console.log(f([7, 6, 5, 4, 3, 2, 1], 4))
console.log(f([1, 2, 3, 4, 5, 6, 7], 6))