Javascript rgb颜色猜谜游戏

Javascript rgb颜色猜谜游戏,javascript,Javascript,为什么第一个代码有效,而第二个代码无效?它表示“未捕获的TypeError:无法读取未定义的属性'style' 在HTMLDIVELENT。” 所有的方块都是div,并且已经在代码中声明了 var colors=[ "rgb(255, 0, 0)", "rgb(255, 255, 0)", "rgb(255, 0, 255)", "rgb(25, 50, 0)", "rgb(2, 0, 50)", "rgb(255, 60, 0)" ] var

为什么第一个代码有效,而第二个代码无效?它表示“未捕获的TypeError:无法读取未定义的属性'style' 在HTMLDIVELENT。”

所有的方块都是div,并且已经在代码中声明了

var colors=[
    "rgb(255, 0, 0)",
    "rgb(255, 255, 0)",
    "rgb(255, 0, 255)",
    "rgb(25, 50, 0)",
    "rgb(2, 0, 50)",
    "rgb(255, 60, 0)"
]

var squares= document.querySelectorAll(".square");

var pickedColor=colors[3];

var colorDisplay= document.getElementById("colorDisplay");

colorDisplay.textContent= pickedColor;

for(var i=0; i<squares.length; i++){
    squares[i].style.backgroundColor = colors[i];
    squares[i].addEventListener("click", function(){
        alert(this.style.backgroundColor);
    }); 


}
var颜色=[
“rgb(255,0,0)”,
“rgb(255,255,0)”,
“rgb(255,0255)”,
“rgb(25,50,0)”,
“rgb(2,0,50)”,
rgb(255,60,0)
]
var squares=document.queryselectoral(“.squares”);
var pickedColor=颜色[3];
var colorDisplay=document.getElementById(“colorDisplay”);
colorDisplay.textContent=pickedColor;
对于(var i=0;i
为什么第一个代码有效,而第二个代码无效
正方形[i]是未定义的,而我已经定义了它

因为在执行事件处理程序时,
i
的值已达到
squares.length

只需将
var
更改为
let

for( let i=0; i<squares.length; i++ ){

for(让i=0;i看起来你拼错了

    alert(sqaures[i].style.backgroundColor);

sqaures->squares

也提供HTML请单击
并提供一个-第二行中的sqaures拼写错误code@charlietfl是的,但这两种密码都是这样吗?我不知道原因though@AryanAgarwal为什么要改变var?让?@ AyayaGARWAL <代码> var <代码>不会放弃PAR绑定因此,它的提升值保留在异步回调处理程序(事件处理程序)中,但是
let
“s”不保留除其当前绑定之外的绑定。
    alert(sqaures[i].style.backgroundColor);