gpt4 book ai didi

Javascript - 使用 document.onkeyup 拼接数组

转载 作者:行者123 更新时间:2023-12-01 03:45:48 25 4
gpt4 key购买 nike

我正在制作一款刽子手游戏。我试图用 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);
}
};

这可能吗?或者我是否必须添加更多行代码才能达到相同的预期效果,因为我知道如何拼接和推送,但似乎不知道这是否可能?我已经搜索了相当长一段时间,似乎只能找到更复杂问题的答案。我知道这是一个基本问题,但我确实需要帮助 - 请并谢谢您。

最佳答案

您可以尝试以下解决方案。如果用户点击按钮并且给定的单词包含该指定字符,则将其从 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
}
});

关于Javascript - 使用 document.onkeyup 拼接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43576670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com