问题描述
我试图通过一系列值获取一组数组元素。
如果我有以下数组:
const arr = ["one","two","three","four","five","six",...]
如果我只想获取前四个元素,我会这样做:
arr.slice(0,4)
// output: ["one","four"]
但是我希望有接下来的四个元素,即我希望我的输出如下:
// output: ["five","six"]
但我想让它变得动态,像这样:
// first set of data (first four)
getData(1)
// second set of data (next four)
getData(2)
我该怎么做?
解决方法
您的 getData
函数可以使用 slice
作为第一个参数和 (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));