javascript - 使用有状态偏移量获取数组的块
问题描述
我试图通过一系列值获取一组数组元素。
如果我有以下数组:
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)
我该怎么做?
解决方案
您的getData
函数可以调用slice
using(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));
推荐阅读
- 3d - 我可以读取应用的 SCNConstraint 的变换矩阵吗?
- javascript - 如何在浏览器中运行 React Native
- javascript - 如何根据 obj 标志的状态查找数组长度
- angular - 茉莉和可观察的
- maven - Selenium Grid Docker-通过 Jenkins 实现自动化
- ios - 自动 TableView 单元格高度无法正常工作
- javascript - MVC 5 中的搜索参数
- ios - 无法安装cordova-plugin-accountkit
- ios - iOS 本地化使用 Xib 和 Swift:有人可以帮助我使用 XIB(不是 Storyboard)和 Swift 制作多语言应用程序吗?
- html - 使用 actionmailer 时如何根据设备类型或屏幕大小调整图像大小?