简体   繁体   English

javascript:为什么这个return语句会导致语法错误?

[英]javascript: Why does this return statement cause a syntax error?

I'm using Apatana 3, i modified the JS code formatter a little bit to let it seem more clear, below is the code after format, it give me an error: 我正在使用Apatana 3,我稍微修改了JS代码格式化程序,让它看起来更清晰,下面是格式化后的代码,它给我一个错误:

    copyOffset : function( index )
    {
        return
        {
            x : index, y : index
        };
    }

firebug give me: 萤火虫给我:

SyntaxError: invalid label

if i change it to: 如果我改为:

    copyOffset : function( index )
    {
        return{
            x : index, y : index
        };
    }

will be OK, Anybody who can tell me what's the diff between these two return statement? 没问题,谁能告诉我这两个回报声明之间的区别是什么?

The difference is that the first snippet is actually interpreted as... 区别在于第一个片段实际上被解释为......

copyOffset : function( index )
{
    return;
    {
        x : index, y : index
    };
}

It's called Automatic Semicolon Insertion : when JavaScript parser sees a statement that seems to be complete, but misses semicolon, it attempts to 'fix' it. 它被称为自动分号插入 :当JavaScript解析器看到一个似乎完整的语句但是没有分号时,它会尝试“修复”它。

And yes, even though helpful at times, it can be quite annoying. 是的,尽管有时很有帮助,但它可能非常烦人。 This article explains this JavaScript feature in details. 本文详细介绍了此JavaScript功能。

Haha, this is a classical one;) 哈哈,这是一个古典的;)

Javasript breaks on Javasript打破了

return
{

because it treats { as a new block and implicitely inserts a semicolon: 因为它将{视为一个新块并且隐含地插入一个分号:

return;
{

thus returning undefined:-D 因此返回undefined:-D

The Problem is Javasript inserting a Semicolon at the end of a line when the statement makes sense. 问题是当语句有意义时,Javasript在一行的末尾插入一个分号。 Since return can stand on it's own, Javascript interprets it as a complete statement and inserts the semicolon, thus breaking your code. 由于return可以独立存在,Javascript会将其解释为完整语句并插入分号,从而破坏您的代码。

Actually, this is the reason, why in Javascript you alway should avoid those newlines and write: 实际上,这就是原因,为什么在Javascript中你总是应该避免这些新行并写:

copyOffset : function( index ){
    return{
        x : index, y : index
    };
}

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

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