js 根据指定个数切割数组
Part.1 问题
写项目时,遇到需要前端做 假分页 的问题:后端会将数据全部返回,前端自己做分页
Part.2 思路
拿到后端全部返回的数据后,按照 产品需求 进行分页,如每页显示 10 条数据为例,则需要将全部数据 按照每 10 条一个小数组进行分割,然后合并为一个大数组,然后根据索引取值
Part.3 例如
我们假设这是后端返回的全部数据
arr: [ {name: '小明', age: 20}, {name: '小红', age: 21}, {name: '小军', age: 22}, {name: '小王', age: 23}, {name: '小朱', age: 24}, {name: '小刘', age: 25}, {name: '小张', age: 26}, {name: '小庞', age: 27}, {name: '小米', age: 28}, {name: '小华', age: 29}, {name: '小郑', age: 30}, {name: '小蓝', age: 31}, {name: '小绿', age: 32}, {name: '小青', age: 33}, {name: '小白', age: 34}, {name: '小黑', age: 35}, {name: '小橙', age: 36}, {name: '小紫', age: 37}, {name: '小山', age: 38}, {name: '小一', age: 39}, {name: '小鹏', age: 40}, {name: '小丛', age: 41}, {name: '小鱼', age: 42}, {name: '小李', age: 43}, {name: '小英', age: 44}, {name: '小杰', age: 45}, {name: '小金', age: 46}, {name: '小窗', age: 47}, {name: '小叶', age: 48}, {name: '小文', age: 49}, {name: '小龙', age: 50}, {name: '小纯', age: 51}, {name: '小伟', age: 52}, {name: '小佳', age: 53}, {name: '小吴', age: 54}, {name: '小枚', age: 55}, {name: '小原', age: 56}, {name: '小书', age: 57}, {name: '小江', age: 58}, {name: '小砚', age: 59}, {name: '小然', age: 60} ],
首先创建一个空数组,用于接收分割完成的小数组
newArr: []
然后根据每页 10 条进行分割
dataHandling: function() { let arrLength = this.arr.length; // 数组长度 let num = 10; // 每页显示 10 条 let index = 0; for (let i = 0; i < arrLength; i++) { if (i % num === 0 && i !== 0) { // 可以被 10 整除 this.newArr.push(this.arr.slice(index, i)); index = i; }; if ((i + 1) === arrLength) { this.newArr.push(this.arr.slice(index, (i + 1))); } }; }
结果如下:
将数据分割成了 5 个小数组,每个小数组为 10条 数据,然后根据分页操作取 大数组(newArr)的索引 就可以完成取值,实现假分页操作了!~~~