为何数组中ASCII码元素的key属性返回undefined?如何获取对应字符?
问题解答:键码转按键名称与ASCII字符转换
为什么代码返回undefined?
你定义的possibleKeyCodes数组里存的是纯数字(键码值),数字本身没有.key属性——.key是键盘事件对象的专属属性,不是数字的属性,所以调用possibleKeyCodes[0].key自然返回undefined。
一、把键码转成对应按键名称
如果想拿到键码对应的按键名称(比如65对应"a"或"A"),可以通过模拟键盘事件来获取:
var possibleKeyCodes = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]; function getKeyName(keyCode) { const event = new KeyboardEvent('keydown', { keyCode }); return event.key; } // 示例:获取第一个键码的按键名称 console.log(getKeyName(possibleKeyCodes[0])); // 输出 "a",要大写就加.toUpperCase()
这种方式通用性强,还能处理字母之外的其他键码(比如回车、空格等)。
二、把ASCII码转成实际字符
你的数组里的65-90是大写英文字母的ASCII码,用String.fromCharCode()就能直接转成对应字符:
var possibleKeyCodes = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]; // 转换单个码 console.log(String.fromCharCode(possibleKeyCodes[0])); // 输出 "A" // 批量转换整个数组 const asciiChars = possibleKeyCodes.map(code => String.fromCharCode(code)); console.log(asciiChars); // 输出 ["A", "B", "C", ..., "Z"]
要是想要小写字符,转换后调用.toLowerCase()就行,比如String.fromCharCode(65).toLowerCase()会返回"a"。
内容的提问来源于stack exchange,提问作者Coolcoder789
相关产品推荐
相关产品推荐

