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.

5
  • 2
    Because [5].toString() === "5". map[{toString: () => "5"}] would give the same result too. See e.g. stackoverflow.com/questions/6066846/…. Commented Feb 26, 2020 at 21:44
  • Converting an array to a string is equivalent to array.join(",") Commented Feb 26, 2020 at 21:46
  • It's basically this thing - the array would be stringified and gets turned to a single "5" Commented Feb 26, 2020 at 21:50
  • 1
    Actually map[[[[[5]]]]] == "five" Yeah, javascript sometimes just sucks. Commented Feb 26, 2020 at 21:50
  • You forgot to mention that "five" == {[[5, 6, 7]]: 'five'}[[5, 6, 7]] also. Commented Feb 26, 2020 at 21:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.