How exactly does the JavaScript expression [1 [{}]] parse?

痴心易碎 提交于 2019-12-03 14:46:18

If we break it up a bit, you'll see:

var foo = 1;
var bar = {};
var baz = foo[bar];

[baz];

I believe it's valid JavaScript, but I'm not an expert...

CMS

Reading the OP and Nick comments, I think I can expand a little bit more the Adrian's answer to make it clearer.

It's perfectly valid JavaScript.

JavaScript handles object property names as strings, objects cannot contain other types or other objects as keys, they are just strings.

The bracket notation property accessor (MemberExpression [ Expression ]) implicitly converts the expression between brackets into a string, so:

var obj = {};
obj[{}] = "foo";
alert(obj["[object Object]"]); // foo

In the above example you can see that I assign a value to the {} property, and {}.toString() (or {}+'') produces the string "[object Object] (via Object.prototype.toString).

The expression 1 [{}] implicitly converts the 1 Number primitive to an object (this is made by the property accessor) and it lookups a property named "[object Object]" the property lookup is made on the Number.prototype and the Object.prototype objects, for example:

1['toString'] === Number.prototype.toString; // true

Finally, the 1 [{}] expression is itself enclosed in brackets ([1 [{}]]), this is actually an Array literal.

In conclusion here is how the parser evaluates the expression:

 [1 [{}]];
 //   ^ The accessor expression is evaluated and converted to string

 [1 ["[object Object]"]];
 // ^ A property lookup is made on an Number object 
 //   trying to access a property named "[object Object]"

 [undefined];
 //   ^ the property is obviously not found

   [undefined];
 //^         ^
 // An array literal is created with an element `0` which its value is `undefined`

It is because you are trying to get the property {} of the object 1 and then place it in an array. 1 doesn't have the property {}, so 1[{}] is undefined.

If you replace the 1 with an array, you will see how it is working. With 1 as [5] and {} as 0, it is [[5][0]].

Also, keep in mind that obj['property'] is the same as obj.property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!