本文实例为大家分享了javascript实现定时器循环展示数组的具体代码,供大家参考,具体内容如下 先看看效果图 流程 使用数组的slice() 方法通过条件判断截取原数组相应内容
本文实例为大家分享了javascript实现定时器循环展示数组的具体代码,供大家参考,具体内容如下
先看看效果图
使用数组的slice() 方法通过条件判断截取原数组相应内容组成新数组
let currentPage = 0
// arr:原数组 newLen:新数组需要的长度 currentPage:现在的页码
// 方法一:
function loopData(arr, newLen) {
let len = arr.length;
let result = len - currentPage;
let newArr = [];
if (result > 0 && result < newLen) {
newArr = [
...arr.slice(currentPage - result, len),
...arr.slice(0, newLen - result),
];
currentPage = newLen - result;
} else if (result >= newLen) {
newArr = arr.slice(currentPage, currentPage + newLen);
currentPage += newLen;
} else {
currentPage = 0;
newArr = arr.slice(currentPage, currentPage + newLen);
}
return newArr;
}
// 方法二:
function loopData(arr, newLen) {
let len = arr.length;
let newArr = [];
if (currentPage === len) { // 页码等于数组长度时,从0重新开始
currentPage = 0;
}
if (currentPage + newLen <= len) {
newArr = [...arr.slice(currentPage, currentPage + newLen)];
currentPage++;
} else if (currentPage + newLen > len && currentPage < len) {
newArr = [
...arr.slice(currentPage, len),
...arr.slice(0, newLen - len + currentPage),
];
currentPage++;
}
return newArr;
}
<template>
<div class="container">
<el-button @click="changeStatus">{{ flag ? "暂停" : "开始" }}</el-button>
{{ list }}
</div>
</template>
<script>
let currentPage = 0;
export default {
data() {
return {
arr: [1, 2, 3, 4, 5, 6, 7],
list: [],
timer: null,
flag: true,
};
},
mounted() {
this.start()
},
destroyed() {
this.timer && clearInterval(this.timer);
},
methods: {
changeStatus() {
if (this.flag) {
this.timer && clearInterval(this.timer);
} else {
this.start();
}
this.flag = !this.flag;
},
start() {
this.timer = setInterval(() => {
this.list = this.loopData(this.arr, 4);
}, 1000);
},
loopData(arr, newLen) {
let len = arr.length;
let newArr = [];
if (currentPage === len) {
currentPage = 0;
}
if (currentPage + newLen <= len) {
newArr = [...arr.slice(currentPage, currentPage + newLen)];
currentPage++;
} else if (currentPage + newLen > len && currentPage < len) {
newArr = [
...arr.slice(currentPage, len),
...arr.slice(0, newLen - len + currentPage),
];
currentPage++;
}
return newArr;
},
},
};
</script>
<style lang="sCSS" scoped>
.container {
padding: 20px;
}
</style>
--结束END--
本文标题: JavaScript实现定时器循环展示数组
本文链接: https://lsjlt.com/news/166540.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0