我有一個小謎題,我無法完全弄清楚!
我需要無限回圈地遍歷兩組數字,首先是一組,然后是另一組。兩者都從 -1 開始,并且都上升到 2。
firstIndex = -1
secondIndex = -1
我可以使用以下方法遍歷第一個數字:
setInterval(() => {
if (firstIndex === 2) {
firstIndex = 0;
} else {
firstIndex
}
}, 10000);
但是我不知道當 firstIndex 為 2 時如何切換到 secondIndex,以便 secondIndex 上升到 2,停止,然后 firstIndex 開始向上計數,停止,然后 secondIndex 開始向上計數......
所以像這樣……
firstIndex = 0, firstIndex = 1, firstIndex = 2,
secondIndex = 0 (firstIndex = -1), secondIndex = 1, secondIndex = 2,
firstIndex = 0 (secondIndex = -1), firstIndex = 1, firstIndex = 2,
secondIndex = 0 (firstIndex = -1), secondIndex = 1, secondIndex = 2…
請幫忙 :)
uj5u.com熱心網友回復:
我會將這些索引存盤在一個陣列中,而不是兩個變數中。這樣,它很容易擴展到 3 個或更多索引。
這是一個實作,其中有 3 個而不是 2 個索引(為了更好地演示這個想法)。在計時器回呼的任何開始,只有一個不等于 -1 的索引:
var max = 2;
var indices = [-1, -1, max]; // put max in last entry
setInterval(() => {
let i = indices.findIndex(n => n !== -1);
indices[i] ;
if (indices[i] > max) {
indices[i] = -1;
indices[(i 1) % indices.length] = 0;
}
console.log(...indices);
}, 300);
此代碼中的分配對陣列元素進行了更新。意識到這里使用陣列而不是兩個(或更多)索引變數(firstIndex, secondIndex),因為這是更好的做法。
所以使用indices[0]你會使用firstIndex的地方和indices[1]你會使用的地方secondIndex。
如果您真的非常想將這些用于變數,那么每次進行更新時都初始化它們,就像這樣(這里我們只使用兩個索引而不是上面的三個):
var max = 2;
var indices = [-1, max]; // put max in last entry
setInterval(() => {
let i = indices.findIndex(n => n !== -1);
indices[i] ;
if (indices[i] > max) {
indices[i] = -1;
indices[(i 1) % indices.length] = 0;
}
let [firstIndex, secondIndex] = indices;
console.log(firstIndex, secondIndex);
}, 300);
uj5u.com熱心網友回復:
您可以獲取一個陣列并使用給定索引遞增該值直到最大值,然后更改索引以遞增另一個索引,依此類推。
let
data = [0, 0],
index = 0;
setInterval(() => {
if ( data[index] > 2) {
data[index] = 0;
index = 1 - index;
}
console.log(...data);
}, 500);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/454298.html
標籤:javascript 循环 for循环
