0

When I have this:

hash = { 1_1: 'foo' }

why hash[1_1] gives undefined, while for ex.:

hash = { 1: 'foo' }

hash[1] returns correct value.

Both objects keys are strings:

typeof Object.keys(hash)[0]  /// -> string

so why it doesnt convert hash[1_1] to string?

p.s. I tested on Chrome and looks like it already supports numeric separators

bigInt
  • 203
  • 5
  • 15

1 Answers1

3

JS engine is disposing of the underscore and converting the key from 1_1 to 11. But if you wrap it in quotes, it will work:

hash = {"1_1": 'foo' }

//{1_1: "foo"}

Further reading: Which characters are valid/invalid in a JSON key name?

Tanner
  • 2,232
  • 13
  • 22
  • Thats a good catch, I was just hoping I can avoid something like `function(param) { hash[ '' + param] // do something }` – bigInt Jun 21 '19 at 14:47
  • @NinaScholz My example came from Chrome - but testing in IE and Edge yield the same result. – Tanner Jun 21 '19 at 15:27