[英]Change colour on every iteration of forEach loop in javascript?
我有一个 function 可以短暂更改元素的颜色,然后将其更改回原始颜色。 根据您所处的级别(这是一个益智游戏),forEach 循环然后运行此 function 一定次数(在更高级别更多)。 目前,元素更改为的颜色是我手动输入到代码中的任何颜色。 每次 forEach 运行 function 时,我都试图找到一种方法来更改该颜色。
例如,假设你在第一轮,forEach 运行了 3 次,元素将为 flash red-white, red-white, red-white。 我需要的是 flash 红白、蓝白、粉白。 当颜色用完时,它还需要循环回到数组的开头。 例如,在更高级别,forEach 可能会运行 6 次,因此对颜色数组的迭代将不得不 go 回到开始一次。 这是代码:
function showCircle(item, j, x) {
setTimeout(function () {
let x = 0;
let colors = ['blue','pink','green']
let color = colors[x];
var num = initArray[j];
var element = document.getElementById(num)
element.classList.add(`cell-glow-${color}`)
window.setTimeout(function () {
element.classList.remove(`cell-glow-${color}`)
}, 400);
j++;
x++
console.log(color)
}, speed() * j);
};
function showEachCircle(captureUserClicks) {
initArray.forEach(showCircle);
}
很明显,上面发生的事情是 showCircle function 每次都将 x 归零,所以它在第一次迭代时卡住了。 但我不确定我应该将这些变量放在哪里以使其正确迭代。 另外,我什至还没有开始考虑将阵列强制转换为 go 回到开头。
有任何想法吗? 谢谢!
问题是您正在覆盖x
并且您正在尝试修改正在传入的数字j
。
首先, forEach 的定义有助于阅读。
具体来说,在您传入的 function 中, showCircle
, item
是数组的当前项, j
是循环的当前索引, x
是原始数组,在这种情况下它将是initArray
。 然后,你用let x = 0
覆盖x
,并且你试图增加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 colors:
0 % colors.length = 0
1 % colors.length = 1
2 % colors.length = 2
3 % colors.length = 0
4 % colors.length = 1
etc..
我会这样做:
为了避免每次调用 function 时都会执行x=0
,我们将把它放在它之外。
要遍历 colors 数组,我们将利用模运算符:
`x = (x+1)%3`
这代替x++
将一遍又一遍地获得值0, 1, 2
。
array.forEach()
将多次调用 function 而无需等待完整的 flash(从白色到红色再到白色)完成。 我们将使用递归。 完成完整的 flash 后,如果需要,我们将再次调用 function。
您可以在代码段中看到一个工作示例:
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();
现在你可以只放你的代码而不是我的控制台日志,你应该让它工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.