今天朋友问我,如何点击一个按钮,每次只展示数组中的五条数据,如果数据有13条,默认展示数组1-5,点第一次为6-10,第二次为11-13,第三次从头再来
方法如下:
change(){ this.arrayShow = []; let index = 0; if (this.index === this.allData.length) { this.index = 0; } for (let i = this.index; i < this.index + 5; i++) { if (this.allData[i]) { this.arrayShow.push(this.allData[i]); index = i; } } this.index = index + 1; }效果:数组最后, 再次点击change重头开始
还有一种方法为循环到最后将数组头尾连接起来显示
changeData1() { this.arrayShow = []; let index = 0; for (let i = this.index; i < this.index + 5; i++) { if (this.allData.length - index === this.allData.length - 5) { let ss = this.allData.splice(0, 5); for (let j = 0; j < ss.length; j++) { this.allData.push(ss[j]); } } index = i; } for (let i = 0; i < 5; i++) { this.arrayShow.push(this.allData[i]); } },效果如下 若有改进之处,望多多指教