简体   繁体   English

为什么“3 [1,2];”在JavaScript中返回undefined?

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

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. 我正在查看GMail所做的一些AJAX调用,我注意到有时调用的返回值以数字开头。 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. 如果我将其输入到JavaScript控制台中,我将返回未定义的内容。 However, if the second parameter is a number or a string, I'd get the second parameter returned back. 但是,如果第二个参数是数字或字符串,我将返回第二个参数。 Example: 例:

3
4

Returns 4. 返回4。

My guess is that they're doing this to stop jsonp-type attacks, however, does anyone know what underlying evaluation is being done? 我的猜测是他们这样做是为了阻止jsonp类攻击,然而,是否有人知道正在进行什么基础评估? In the 2nd case I believe that a semi-colon is "inserted" after the first line, which would make returning 4 make sense. 在第二种情况下,我相信在第一行之后“插入”一个分号,这将使返回4有意义。 However, I can't think of a reason why the first expression would return undefined. 但是,我想不出第一个表达式返回undefined的原因。

This is because how ASI ( Automatic Semicolon Insertion ) works. 这是因为ASI(自动分号插入)的工作原理。 The first statement is interpreted as 第一个语句被解释为

3[1,2];

so it is undefined . 所以它是undefined The second one is interpreted by ASI as 3;4; 第二个被ASI解释为3;4; which is 4 . 这是4

ASI rules are counterintuitive in some cases, for example you might wonder why there is no semicolon between number and bracket? 在某些情况下,ASI规则是违反直觉的,例如,您可能想知道为什么数字和括号之间没有分号? Well, there is a reason for that. 嗯,这是有原因的。 Read these resources for more details: 阅读这些资源以获取更多详细信

What are the rules for JavaScript's automatic semicolon insertion (ASI)? JavaScript的自动分号插入(ASI)有哪些规则?

http://bclary.com/2004/11/07/#a-7.9.1 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. :)这就是为什么我们有无尽的无分号JavaScript战争。

This is to prevent the Ajax JSON hack changing the Array constructor. 这是为了防止Ajax JSON破解更改Array构造函数。 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. hack重写了Array构造函数,因此当读取JSON时,代码将执行构造函数的操作。 More explanation here: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx 这里有更多解释: 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: []} . 顺便说一下,这就是为什么ASP.NET总是发回这种对象的原因: {d: []}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM