2014-12-05 220 views
-1

我不明白为什么下面的函数不返回{bar:“hello”},而是返回undefined。为什么这个函数返回undefined?

function foo2() { 
    return 
    { 
     bar: "hello" 
    }; 
} 
+3

'return'之后,在大括号之前有一个回车符。尝试'返回{'而不是。 – sherb 2014-12-05 05:30:21

+2

您可能想要在JavaScript中阅读[自动分号插入](http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)。 – Ben 2014-12-05 05:31:48

回答

5

这是因为它编译为以下,因为JavaScript的自动分号插入。

function foo2() { 
    return; // notice the semi-colon here? 
    { 
     bar: "hello" 
    }; 
} 

而且,由于return;被调用时,函数终止而不要去的下一行代码。 为了让它正常工作,只需在return之后将右括号正确地放在return {之间

您最好使用分号而不是忽略它们。想要理由?检出Dangers of Javascript's automatic semicolon insertion

+0

请注意,这是几乎所有JS教程,样式指南,书籍等在JS历史中创建的ASI危险的*精确*示例。任何花费3秒时间学习JS的人都知道这一点。 – 2014-12-05 05:32:20

+0

嗯,_maybe_ 4秒... :-) – sherb 2014-12-06 00:08:47

1

JS引擎在return之后插入分号。

function foo2() { 
    return; 
    { 
     bar: "hello" 
    }; 
} 

更改为这是确定

function foo2() { 
    return { 
     bar: "hello" 
    }; 
} 

关于自动插入分号,又名ASI,你可能需要阅读thisthisthis