Javascript 循环仅迭代一次| JS
我有这个:Javascript 循环仅迭代一次| JS,javascript,Javascript,我有这个: for (i=0; i < elements.length; i++){ temp = elements[i].querySelectorAll(".fill"); tempArr = Array.from(temp); color = colors[Math.floor(Math.random() * colors.length)];
for (i=0; i < elements.length; i++){
temp = elements[i].querySelectorAll(".fill");
tempArr = Array.from(temp);
color = colors[Math.floor(Math.random() * colors.length)];
for (i of tempArr){
i.style.backgroundColor = color;
}
if (i == 1){
console.log("hi")
}
}
for(i=0;i
它只迭代一次。我有控制台日志作为测试。我没有收到任何错误,因此我也不知道我是否做错了什么。您正在覆盖这一行的
I
:
for (i of tempArr){
使用不同的变量:
for (i=0; i < elements.length; i++){
temp = elements[i].querySelectorAll(".fill");
tempArr = Array.from(temp);
color = colors[Math.floor(Math.random() * colors.length)];
for (j of tempArr){
j.style.backgroundColor = color;
}
if (i == 1){
console.log("hi")
}
}
for(i=0;i
我创建了在for循环之前写入的元素<代码>变量元素=document.querySelectorAll(“.category”)代码>您好,下面的答案是正确的。在第二个内部循环中,应该使用代替(tempArr的j){}
(使用j
代替i
)。即使是大师们在疲劳时也会犯的常见错误。:-)