这个问题在这里已有答案:
window.addEventListener('keydown', (e) => {
let arrowsObj = {
"ArrowUp": 1,
"ArrowDown": 2,
"ArrowLeft": 3,
"ArrowRight": 4
}
let eventKey = e.key;
console.log(arrowsObj.eventKey);
});
上面的代码不起作用,所以我做了以下检查:
arrowsObj.hasOwnProperty(eventKey)
if(eventKey in arrowsObj)
两者都回归真实,我错过了什么?那是因为数据类型吗?
谢谢!
在您的情况下,您不能使用.dot
表示法来访问对象的值,因为它不是字符串键,而是存储键的变量。
使用括号表示法而不是arrowsObj[eventKey]
我仍然建议您使用.hasOwnProperty
,否则如果您按箭头键以外的其他键,那么您将在控制台中得到未定义。
window.addEventListener('keydown', (e) => {
let arrowsObj = {
"ArrowUp": 1,
"ArrowDown": 2,
"ArrowLeft": 3,
"ArrowRight": 4
}
let eventKey = e.key;
console.log(arrowsObj[eventKey]);
});
使用括号表示qazxsw poi而不是点