无法在 keyDown 或 keyPress 事件处理程序中调用函数

Can't call function within keyDown or keyPress event handlers

无法在 keyDown 或 keyPress 事件处理程序中调用函数。

 var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];

$(document).on("keydown",  nextSequence);

function nextSequence() {
   var randomNum = Math.floor(Math.random() * 4);
   var randomChosenColor = buttonColors[randomNum];
   return gamePattern.push(randomChosenColor);
}

您可能不需要 return,因为您的变量在回调之外。正如@Samathingamajig 指出的那样,它确实有效。您还可以调用 keydown shorthand 版本

$(document).keydown(function () {
    var randomNum = Math.floor(Math.random() * 4);
    var randomChosenColor = buttonColors[randomNum];
    gamePattern.push(randomChosenColor);
    // Check the current state of gamePattern
    console.log(gamePattern);

});