未捕获的TypeError:无法设置undefined的属性

时间:2012-01-16 08:40:27

标签: javascript html5-canvas

Google Chrome正在投掷" Uncaught TypeError:无法设置属性' isDown'未定义"但我的代码看起来没有任何问题!

我的变量数组的重要部分:

KEY = {
    UP: 38,
    DOWN: 40,
    W: 87,
    S: 83,
    D: 68
}
pingpong = {
    fps: 60,
    pressedKeys: [],
    complete: false,
}

密钥监听器初始化(这是抛出错误的地方):

    for (var keyCode in KEY) {
        if (KEY.hasOwnProperty(keyCode)) {
            pingpong.pressedKeys[KEY[keyCode]] = {
                isDown: false,
                wasDown: false
            };
        }
    }
    $(document).keydown(function(e) {
        pingpong.pressedKeys[e.which].isDown = true;
    });
    $(document).keyup(function(e) {
/* This line is the issue */    pingpong.pressedKeys[e.which].isDown = false;
    });

任何想法?

2 个答案:

答案 0 :(得分:2)

问题是您正在尝试访问不存在的pressedKeys数组元素。例如,如果我们按下“a”键:

$(document).keyup(function(e) {
    //Pressed "a" so e.which == 65
    pingpong.pressedKeys[e.which].isDown = false;
});

初始化数组时,只需为KEY对象的属性创建元素:

for (var keyCode in KEY) {
    //Iterating over KEY, which contains 5 properties...
    if (KEY.hasOwnProperty(keyCode)) {
        //Add value to pressedKeys (this happens for each of the 5 properties)
        pingpong.pressedKeys[KEY[keyCode]] = {
            isDown: false,
            wasDown: false
        };
    }
}

所以pressedKeys只包含5个元素,对应KEY的属性。请注意,keydown事件处理程序以及keyup中也会引发TypeError。

要修复它,您可以检查e.which是否在事件处理函数中的KEYS对象中。如果不是,请忽略它。也许是这样的事情(可能有更好的方式,这就是首先想到的):

$(document).keydown(function(e) {
    for(var k in KEY) {
        if(KEY[k] == e.which) {
            break; //Break out of loop and execute last line
        }
        return false; //Key not recognized, last line is not executed
    }
    pingpong.pressedKeys[e.which].isDown = true;
});

答案 1 :(得分:1)

e.which仅限IE。真正的浏览器使用e.keyCode

jQuery Event Keypress: Which key was pressed?