Why does “3 [1, 2];” return undefined in JavaScript?

…衆ロ難τιáo~ 提交于 2019-12-04 16:26:54

问题


I was looking at some of the AJAX calls that GMail does, and I noticed that sometimes the return value of the calls started with a number. Example: (note that there's is no semi-colon after the first line)

3 
[1, 2];

If I were to enter this into a JavaScript console, I'd get undefined returned back. However, if the second parameter is a number or a string, I'd get the second parameter returned back. Example:

3
4

Returns 4.

My guess is that they're doing this to stop jsonp-type attacks, however, does anyone know what underlying evaluation is being done? In the 2nd case I believe that a semi-colon is "inserted" after the first line, which would make returning 4 make sense. However, I can't think of a reason why the first expression would return undefined.


回答1:


This is because how ASI ( Automatic Semicolon Insertion ) works. The first statement is interpreted as

3[1,2];

so it is undefined. The second one is interpreted by ASI as 3;4; which is 4.

ASI rules are counterintuitive in some cases, for example you might wonder why there is no semicolon between number and bracket? Well, there is a reason for that. Read these resources for more details:

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

http://bclary.com/2004/11/07/#a-7.9.1

Google will probably give you more results. :) That's why we have neverending semicolon-free JavaScript war.




回答2:


This is to prevent the Ajax JSON hack changing the Array constructor. This is an old bug, not relevant in modern browsers, but which has to be handled.

The hack is overriding the Array constructor, thus when the JSON is read, the code will do what the constructor does. More explanation here: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

By the way, this is why ASP.NET always sends back objects of this kind: {d: []}.



来源:https://stackoverflow.com/questions/14631105/why-does-3-1-2-return-undefined-in-javascript

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