Javascript - 使用document.onkeyup拼接数组

时间:2017-04-23 21:26:20

标签: javascript arrays function

我正在建立一个刽子手游戏。我试图用document.onkeyup捕获用户猜测,然后从数组中拼接该项。如果用户做出了正确的猜测,那就是。这是我的功能:

var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var i = alphabet.indexOf;

document.onkeyup = function(event) {
  console.log("event=", event);
  var userGuess = String.fromCharCode(event.which).toLowerCase();

  if (userGuess === alphabet[1] || alphabet[2] || alphabet[3]) {

    alphabet.splice(i, 1 || 2 || 3);
    console.log(alphabet);
  }
};

这可能吗?或者我必须添加更多行代码才能达到相同的效果,因为我知道如何拼接和推送,似乎无法弄清楚这是否可行? 我一直在谷歌上搜索一段时间,似乎只能找到更复杂问题的答案。我知道这是一个基本问题,但我真的可以使用这个帮助 - 拜托并谢谢你。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下解决方案。如果用户点击按钮并且给定的单词包含指定的字符,请将其从alphabet数组中删除。随意修改它。

var words = "One apple a day",
    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

document.addEventListener('keyup', function(e) { //listen to the keyboard events
  if (e.keyCode > 64 && e.keyCode < 91 && alphabet.indexOf(e.key) > -1) { //to avoid spam with logs, we will restrict the range of keycodes from 64 to 91 (a-z) ===> a keycode is 65, z is 90 
    if (words.indexOf(e.key) > -1) { //if clicked letter is included inside the words
      alphabet.splice(alphabet.indexOf(e.key), 1); //then remove it from the alphabet
      console.log('correct letter');
    } else {
      console.log('incorrect letter');
    }
    console.log(JSON.stringify(alphabet)); //show the alphabet and its actual state
  }
});