如何在JavaScript中按下键并放入数组?

OOP*_*rog 2 javascript keyboard keypress

如何获取按下的键,而不是返回键代码,将该键放入数组?

例如,用户将按'a'.然后,代码将'a' - 而不是字符的键代码 - 放入数组中.

提前致谢!

Dan*_*llo 7

这样的事情怎么样?

var your_array = [];

document.onkeydown = function (e) {
  var keyPress;

  if (typeof event !== 'undefined') {
    keyPress = event.keyCode;
  }
  else if (e) {
    keyPress = e.which;
  }

  your_array.push(String.fromCharCode(keyPress));

  return false;   // Prevents the default action
};
Run Code Online (Sandbox Code Playgroud)

更新:如果您需要准确的字符信息(例如,大写与小写的区别,以及其他内容),请务必查看下面的@Tim Down的评论和他的其他答案.