【问题标题】:Cycle numbers of array with JavaScriptJavaScript 数组的循环数
【发布时间】:2018-07-09 01:37:57
【问题描述】:
我正在尝试使用 JavaScript 循环类似于此的数组。 arr0=[0,1,2,3] 我想将数组中的最后一个数字循环到第一个索引并继续循环遍历数组数字。我尝试使用间隔和移位推送和弹出,但我无法使数组循环。
outArr0 = [0, 1, 2, 3];
var cou0 = -1;
var int0 = setInterval(function() {
cou0++
var pushThis0 = outArr0[outArr0.length - 1];
outArr0.pop();
outArr0.shift();
outArr0[0] = pushThis0;
console.log(outArr0);
if (cou0 == 6) {
clearInterval(int0)
}
}, 500);
【问题讨论】:
标签:
javascript
arrays
cycle
【解决方案1】:
请检查以下代码,刚刚修复了您的代码,
outArr0 = [0, 1, 2, 3];
var cou0 = -1;
var int0 = setInterval(function() {
cou0++
console.log(outArr0[0]);
outArr0.push(outArr0.shift());
//
if (cou0 == 6) {
clearInterval(int0)
}
}, 500);
【解决方案2】:
要循环,您只需要一个索引,如果它到达数组长度的末尾,它将重置。您可以使用模运算符来实现这一点。
function cycle() {
let index = 0;
let arr = [0,1,2,3];
return function() {
console.log(arr[index++ % (arr.length)]);
}
}
setInterval(cycle(), 500);
【解决方案3】:
这是你如何在元素之间循环往复...
var outArr = [0, 1, 2, 3];
for (i = outArr.length; i!=-1; i--){
console.log(outArr[i]);
}
【解决方案4】:
如果我正确理解您的问题,我相信这会有所帮助
为了清楚起见,我添加了 cmets。
//define a function to cycle the array
function cycleArray(theArray)
{
//store the last value in the array
var _tmp = theArray[theArray.length-1];
//iterate from last to first element, pulling the element from the prev. index
for(i = theArray.length-1; i > 0; i--)
{
theArray[i] = theArray[i-1];
}
//place the saved last element into the first slot of the array
theArray[0] = _tmp;
}
如何使用该功能:
//define your array
someArray = [0, 1, 2, 3];
alert(someArray.toString());
//cycle the array
cycleArray(someArray);
alert(someArray.toString());
上面的代码产生以下内容:
0,1,2,3
3,0,1,2
漂亮而简单。希望我正确理解了您的问题。