对数组中的内容进行换位,每隔1s
- 思路:循环 新数组 间隔调用
- 技术:for 循环( 或者你擅长的循环) 函数
- 举例:结果[1, 2, 3, 4, 5, 6, 7]—>[2, 3, 4, 5, 6, 7, 1]—>[3, 4, 5, 6, 7, 1, 2]…
- js代码如下:
let mylist = [1, 2, 3, 4, 5, 6, 7]
function ReversalData(mylist) {
let startItem = mylist[0]; // 获取数组中的第一项 第一项要放到最后
let newList = []; // 声明一个空数组
mylist.forEach((item, index)=> { // 对当前数组进行循环遍历
if(index !== 0){ // 不添加第一个数据
newList.push(item) // 新的数组把除了第一个的元素,push到新的数组中
}
})
newList.push(startItem)// 最后把第一追加到新数组中的最后一项
return newList // 此时数组会变成[2, 3, 4, 5, 6, 7, 1]
}
function TimingCall(time) { // 间隔调用的函数
let result = ReversalData(mylist) // 调用操作数据的函数 得到操作后的数组
setInterval(()=> {
result = ReversalData(result) // 每隔1s就把操作后的数据传进去,再次操作
console.log(result, 'result')
}, time)
}
// 时间,间隔调用的时间
TimingCall(1000)