Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does accessing an element in an object using an array as a key work?

Tags:

javascript

What do you make of this?

var x = {a: 1};         //=> {a: 1}
var y = Object.keys(x); //=> ['a']
x[y]                    //=> 1

if y = ['a'], x[y] is the same as doing x[['a']], right?

x[['a']];               //=> 1

x[[['a']]];             //=> 1

x[[[[[[[['a']]]]]]]];   //=> 1

Can someone explain what's happening here? Why does this work?

like image 415
Mulan Avatar asked May 28 '15 08:05

Mulan


1 Answers

Property names have to be strings. If you try to use an array as a property name, it gets its toString() method called implicitly. That generates a string containing a comma-separated list of its values.

> var array = ['a', 'b', 'c'];
undefined
> array.toString();
'a,b,c'

If you only have one value, then there aren't any commas.

> var array = ['a'];
undefined
> array.toString();
'a'
like image 161
Quentin Avatar answered Oct 07 '22 23:10

Quentin