JavaScript Konami 代码问题包含代码

问题描述

我对 JavaScript 完全陌生,所以请原谅我缺乏知识。如果有人能告诉我我做错了什么(未触发警报“万岁”),我将不胜感激。代码如下:

const codes = [
  "ArrowUp","ArrowUp","ArrowDown","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;
      }
    }
  });
}

解决方法

函数 init() 永远不会被调用,函数 onKeyDownHandler() 也不会被调用。一种方法是简单地删除此内部函数,确保您的 event (e) 与您传递给 addEventListener() 的名称相同。

以下显示了一个工作示例:

const codes = [
  "ArrowUp","ArrowUp","ArrowDown","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;
  }
});

,

您的 init() 可能没有被调用。
这是一个工作演示:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>hello</title>
    <script>
        const codes = [
            "ArrowUp","a"
        ];
        let index = 0;
        window.onkeydown = function (e) {
            const key = e.key;
            if (key === codes[index]) {
                index++;
                if (index === codes.length) {
                    alert("Hurray");
                    index = 0;
                }
            } else {
                index = 0;
            }
        }

    </script>
</head>
<body>
    hello
</body>
</html>  

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...