-3

This comes out as undefined. Why is this?

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(possibleKeyCodes[0].key);

I expected it to give me a key name as a string. It just gave me an undefined.

  • 1
    Since when do numbers have a `key` property? What “key name” are you talking about? – Sebastian Simon Nov 01 '22 at 06:19
  • Why have you added `.key` at the end? – Ankit Nov 01 '22 at 06:22
  • 1
    You mean the [`key`](//developer.mozilla.org/en/docs/Web/API/KeyboardEvent/key) from a keyboard event? Consider using the [`code`](//developer.mozilla.org/en/docs/Web/API/KeyboardEvent/code) property of such an event, or even better, the `data` property of an [`input` event](//developer.mozilla.org/en/docs/Web/API/InputEvent#instance_properties). Other than that, this is a duplicate of [How to create a string or char from an ASCII value in JavaScript?](/q/602020/4642212). – Sebastian Simon Nov 01 '22 at 06:30
  • I now realize that this post is a duplicate. I cannot delete it, but I am sorry. – Coolcoder789 Nov 01 '22 at 06:38

2 Answers2

0
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(possibleKeyCodes[0].key);

Your array is an array of numbers. You are trying to treat an element of this array as it is an object with key property

If you need the ascii repreentation of that number you can do it like that

console.log(String.fromCharCode(possibleKeyCodes[0]))

Or as a snippet

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]))
Manos Kounelakis
  • 2,848
  • 5
  • 31
  • 55
-1

Key ? WHat is Key ??? What is your need ? value or Index ? To get the value inside an array this way is ok

console.log(possibleKeyCodes[0]) // 65
console.log(possibleKeyCodes[1]) // 66
console.log(possibleKeyCodes[5]) // 70

for get index of value

console.log(possibleKeyCodes.findIndex(x=>x==65));