Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - 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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...