2 回答
TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
問(wèn)題是您正在覆蓋并且您正在嘗試修改傳入的x數(shù)字。j
首先,forEach 的定義有助于閱讀。
具體來(lái)說(shuō),在您傳入的函數(shù)中,showCircle是item數(shù)組的當(dāng)前項(xiàng),j是循環(huán)的當(dāng)前索引,x是原始數(shù)組,在本例中為initArray。然后,您用 覆蓋x,let x = 0并嘗試遞增j,這不會(huì)執(zhí)行任何操作,因?yàn)樗谑褂煤髸?huì)遞增。
我認(rèn)為您正在尋找更像這樣的東西:
// 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);
}
如果您不熟悉模數(shù)(或余數(shù))運(yùn)算 %符,那么當(dāng)您想要循環(huán)的內(nèi)容有限時(shí)(在本例中),它對(duì)于循環(huán)非常有用colors。在此示例中,有 3 種顏色:
0 % colors.length = 0
1 % colors.length = 1
2 % colors.length = 2
3 % colors.length = 0
4 % colors.length = 1
etc..
TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
我就是這樣做的:
為了避免
x=0每次調(diào)用函數(shù)時(shí)都被執(zhí)行,我們將把它放在函數(shù)之外。為了迭代顏色數(shù)組,我們將利用模運(yùn)算符:
`x = (x+1)%3`
這將一次又一次地
x++獲取值。0, 1, 2array.forEach()將多次調(diào)用該函數(shù),而無(wú)需等待完整的閃爍(從白色到紅色,再回到白色)完成。我們將使用遞歸來(lái)代替。完整的閃存完成后,如果需要,我們將再次調(diào)用該函數(shù)。
您可以在代碼片段中看到一個(gè)工作示例:
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();
現(xiàn)在你可以把你的代碼代替我的控制臺(tái)日志,你應(yīng)該讓它工作
添加回答
舉報(bào)
