1

See this example:

> map = { 5: 'five' }
> map[5] 
'five' // Makes sense
> arr = [5]
> map[arr]
'five' // Does not make sense
> arr = [5,6,7]
> map[arr]
undefined // I'm cool with that

So when I access an object's property with an array of length 1, it behaves as if I simply input the single element instead of the array. But when the array's length is anything but 1, it will produce the expected behavior.

What is the purpose of this behavior? To me this would simply make things harder for a developer to find a bug in their code.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kebab-case
  • 1,732
  • 1
  • 13
  • 24
  • 2
    Because `[5].toString() === "5"`. `map[{toString: () => "5"}]` would give the same result too. See e.g. https://stackoverflow.com/questions/6066846/keys-in-javascript-objects-can-only-be-strings. – jonrsharpe Feb 26 '20 at 21:44
  • Converting an array to a string is equivalent to `array.join(",")` – Barmar Feb 26 '20 at 21:46
  • It's basically [this thing](https://stackoverflow.com/questions/60061627/mdn-reference-for-using-hasownproperty-with-bracket-notation/60061794#60061794) - the array would be stringified and gets turned to a single `"5"` – VLAZ Feb 26 '20 at 21:50
  • 1
    Actually `map[[[[[5]]]]] == "five"` Yeah, javascript sometimes just sucks. – glinda93 Feb 26 '20 at 21:50
  • You forgot to mention that `"five" == {[[5, 6, 7]]: 'five'}[[5, 6, 7]]` also. – Robert Feb 26 '20 at 21:57

1 Answers1

1

If an object index is not a string or Symbol, it's converted to a string as if by its toString() method.

array.toString() performs the equivalent array.join(",").

So

map[arr]

is equivalent to

map[arr.join(",")]

If the array has one element, joining it simply returns that one element converted to a string, so it's equivalent to

map[arr[0].toString()]

and that explains your first result.

But in your second example, it returns the string "5,6,7" and there's no property with that name in the object.

Barmar
  • 741,623
  • 53
  • 500
  • 612