javascript - JavaScript Konami 代码问题。包含代码
问题描述
我对 JavaScript 完全陌生,所以请原谅我缺乏知识。如果有人能告诉我我做错了什么,我将不胜感激(警报“万岁”未触发)。这是代码:
const codes = [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a"
];
let index = 0;
function init() {
document.body.addEventListener("keydown", (event) => {
function onKeyDownHandler(e) {
const key = e.key;
if (key === codes[index]) {
index++;
if (index === codes.length) {
alert("Hurray");
index = 0;
}
} else {
index = 0;
}
}
});
}
解决方案
functioninit()
永远不会被调用, function 也不会onKeyDownHandler()
。一种方法是简单地删除这个内部函数,确保您的event
( e
) 与您传递给addEventListener()
.
下面显示了一个工作示例:
const codes = [
"ArrowUp", "ArrowUp", "ArrowDown", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "b", "a"
];
let index = 0;
document.addEventListener("keydown", (e) => {
const key = e.key;
if (key === codes[index]) {
index++;
if (index === codes.length) {
alert("Hurray");
index = 0;
}
} else {
index = 0;
}
});
推荐阅读
- python - 错误 1273 但我的架构不包含 utf8mb4_0900_ai_ci
- python - 应用程序配置文件未在 Django 应用程序中返回正确名称
- google-sheets - 如何仅计算 googlesheets 中的特定单词
- scala - 如何使用 Azure Databricks 中的命令清除一个笔记本的状态而不影响其他笔记本?
- angular - 在Angular 8中将表体与n列绑定
- domain-driven-design - DDD 可重用模型
- java - 本地主机以外的 Tomcat9 Web 访问失败
- html - 使项目仅在 xs 屏幕的下拉按钮中可见
- python - TypeError:预期的字符串或类似字节的object.in django
- c# - 循环中的异步睡眠