JS实现数组每次只显示5条数据,首尾相连显示

JS实现数组每次只显示5条数据,首尾相连显示

今天朋友问我,如何点击一个按钮,每次只展示数组中的五条数据,如果数据有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]);
	}
},

效果如下
在这里插入图片描述
若有改进之处,望多多指教

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值