首页 > 解决方案 > 使用有状态偏移量获取数组的块

问题描述

我试图通过一系列值获取一组数组元素。

如果我有以下数组:

const arr = ["one", "two", "three", "four", "five", "six", ...]

如果我只想获得前四个元素,我会这样做:

arr.slice(0, 4)
// output: ["one", "two", "three", "four"]

但是我想要接下来的四个元素,也就是说,我希望我的输出如下:

// output: ["five", "six"]

但我想让它动态化,如下所示:

// first set of data (first four)
getData(1)
// second set of data (next four)
getData(2)

我该怎么做?

标签: javascriptarrays

解决方案


您的getData函数可以调用sliceusing(num - 1) * 4作为第一个参数和num * 4第二个参数:

const arr = ["one", "two", "three", "four", "five", "six"]

function getData(offset) {
  return arr.slice((offset - 1) * 4, offset * 4);
}

console.log(getData(1), getData(2));


推荐阅读