Onkeypress 函数返回空格而不是字母

Onkeypress function returning spaces instead of letters

我正在使用以下内容并尝试让用户猜测的字母出现在屏幕上,但是当我检查 devtools 时,按键被返回到数组,如 [ , , , , , ,]。没有字母。想法?

var letguessText = document.getElementById("letguess")
var guessArray = []

document.onkeypress = function(event) {
  var guess = event.key

  guessArray.push(String.fromCharCode(guess));
  letguessText.textContent = guessArray;
}

您不需要 fromCharCode 因为 event.key 是字符。这是一个例子。

var letguessText = document.getElementById("letguess")
var guessArray = []

document.onkeypress = function(event) {
  var guess = event.key
  guessArray.push(guess);
  letguessText.textContent = guessArray;
}
<p id="letguess">Start typing</p>