为什么"3 [1,2];"返回未定义的JavaScript? [英] Why does "3 [1, 2];" return undefined in JavaScript?
问题描述
我正在查看GMail所做的一些AJAX调用,并且我发现有时调用的返回值以数字开头.示例:(请注意,第一行之后没有分号)
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];
如果我将其输入到JavaScript控制台中,我将得到未定义的返回.但是,如果第二个参数是数字或字符串,则可以返回第二个参数.示例:
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
返回4.
我的猜测是,他们正在这样做以阻止jsonp型攻击,但是,有人知道正在进行什么基础评估吗?在第二种情况下,我认为在第一行之后插入"了分号,这将使返回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.
推荐答案
这是因为ASI(自动分号插入)的工作方式.第一条语句解释为
This is because how ASI ( Automatic Semicolon Insertion ) works. The first statement is interpreted as
3[1,2];
所以它是undefined
.第二个被ASI解释为3;4;
,即4
.
so it is undefined
. The second one is interpreted by ASI as 3;4;
which is 4
.
在某些情况下,ASI规则是违反直觉的,例如,您可能想知道为什么数字和括号之间没有分号?好吧,这是有原因的.阅读这些资源以获取更多详细信息:
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:
> JavaScript自动分号插入(ASI)的规则是什么)?
http://bclary.com/2004/11/07/#a-7.9.1
Google可能会为您带来更多结果. :)这就是为什么我们永无止境的无分号JavaScript 战争.
Google will probably give you more results. :) That's why we have neverending semicolon-free JavaScript war.
这篇关于为什么"3 [1,2];"返回未定义的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!