首页 > 解决方案 > 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;
      }
    }
  });
}

标签: javascriptdom-eventsonkeydown

解决方案


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;
  }
});


推荐阅读