游戏循环似乎在遍历数组结束时中断。未捕获的类型错误

Game loop appears to be breaking at the end of iterating through array. Uncaught TypeError

大家早上好,

这里绝对是一个新手问题,这是我的第一个真正的 JS 项目 - 所以提前为笨拙的代码道歉。

以下函数用于显示 "simon" 游戏的灯光序列。代码最初似乎工作正常,因为我测试了多个长度的数组,但是在退出循环时出现以下错误:

Uncaught TypeError: Cannot read property 'setAttribute' of null
    at show (script.js:95)
    at showLights (script.js:83)
    at script.js:88

我已经四处寻找此错误的修复方法,大部分反馈是它与 DOM 相关,包装器将修复。我发现包装器无法解析。同样,我看不出这是 CSS 或 HTML 的问题,因为函数在退出之前工作正常。

循环函数复制如下:

// iterates through simon.array then allows button press
function showLights(x) {
    if (x >= simon.array.length) {
        clearTimeout(timer);
        show(x);
        allowPress();
    } else {
        show(x);
        var timer = setTimeout(function(){
        showLights(x+1);
        },500);
    } 
}   
// adds then removes flash class to light pads. 
function show(x){ 
    var display = document.getElementById("light" + simon.array[x]);
    display.setAttribute("class", "flasher");
    setTimeout(function(){
        display.setAttribute("class", "game-box");
    },500);
}

对于发布此内容时出现的任何错误或失礼,我们深表歉意。我强烈怀疑当这个问题得到解决时我会很生气。

亲切的问候

安迪

此问题与您检查数组的长度,然后尝试使用该数组中不存在的元素有关。您可能还试图将属性设置为不存在的元素。

据推测,这是问题的真正原因:

if (x >= simon.array.length) {
    clearTimeout(timer);
    show(x);
    allowPress();

简单地删除 show(x) 应该会有帮助。原因是您正在检查 simon.array 的长度,然后稍后在 function show(x) 中请求 simon.array[x],但不会找到任何内容,因为 x大于该数组的长度。

另一个可能的问题出现在以下块中,但可以通过多种方式解决。一种方法是在通过之前检查 x。另一个是在设置属性之前确保元素 (display) 不是 null

// adds then removes flash class to light pads. 
function show(x){ 
    var display = document.getElementById("light" + simon.array[x]);
    display.setAttribute("class", "flasher");
    setTimeout(function(){
        display.setAttribute("class", "game-box");
    },500);
}

我的建议是:

// adds then removes flash class to light pads. 
function show(x){ 
    var display = document.getElementById("light" + simon.array[x]);
    if (display) {
        display.setAttribute("class", "flasher");
        setTimeout(function(){
            display.setAttribute("class", "game-box");
        },500);
    }
}

您可能想查看 classList 以及 setAttribute 的替代方法。

除了使用 setTimeout 之外还需要考虑的其他事项是使用 CSS animation.