2 回答

TA貢獻2036條經驗 獲得超8個贊
問題是您正在覆蓋并且您正在嘗試修改傳入的x
數字。j
首先,forEach 的定義有助于閱讀。
具體來說,在您傳入的函數中,showCircle
是item
數組的當前項,j
是循環的當前索引,x
是原始數組,在本例中為initArray
。然后,您用 覆蓋x
,let x = 0
并嘗試遞增j
,這不會執行任何操作,因為它在使用后會遞增。
我認為您正在尋找更像這樣的東西:
// Declare these outside the loop
var x = 0;
var colors = ['blue','pink','green'];
function showCircle(num, j) {
? // Save the current value so it isn't overwritten by the loop/setTimeout combination
? let y = x;
? // Increment x
? x++;
? setTimeout(function () {
? ? // Get the color, using the modulus operator (%) to start at the beginning again
? ? var color = colors[y % colors.length];
? ? // Get the element. num is the current item in the loop from initArray
? ? var element = document.getElementById(num);
? ? // Make it glow!
? ? element.classList.add(`cell-glow-${color}`)
? ? setTimeout(function () {
? ? ? // Make it not glow...
? ? ? element.classList.remove(`cell-glow-${color}`)
? ? }, 400);
? ? console.log(color);
? ? // j is the index of num in initArray
? }, speed() * j);
};
function showEachCircle(captureUserClicks) {
? initArray.forEach(showCircle);
}
如果您不熟悉模數(或余數)運算 %符,那么當您想要循環的內容有限時(在本例中),它對于循環非常有用colors。在此示例中,有 3 種顏色:
0 % colors.length = 0
1 % colors.length = 1
2 % colors.length = 2
3 % colors.length = 0
4 % colors.length = 1
etc..

TA貢獻1821條經驗 獲得超6個贊
我就是這樣做的:
為了避免
x=0
每次調用函數時都被執行,我們將把它放在函數之外。為了迭代顏色數組,我們將利用模運算符:
`x = (x+1)%3`
這將一次又一次地
x++
獲取值。0, 1, 2
array.forEach()
將多次調用該函數,而無需等待完整的閃爍(從白色到紅色,再回到白色)完成。我們將使用遞歸來代替。完整的閃存完成后,如果需要,我們將再次調用該函數。
您可以在代碼片段中看到一個工作示例:
const initArray = [1,1,1,1,1,1];
const colors = ['red', 'green', 'blue'];
let x = 0;
let numberOfFlashes = 0;
function showCircle() {
setTimeout(()=> {
color = colors[x];
console.log(color);
setTimeout(()=> {
console.log('white');
numberOfFlashes++;
if(numberOfFlashes<initArray.length){
showCircle();
}
}, 400);
x = (x+1)%3;
}, 400);
}
showCircle();
現在你可以把你的代碼代替我的控制臺日志,你應該讓它工作
添加回答
舉報