javascript函数返回undefined而不是object literal

时间:2016-07-27 18:32:33

标签: javascript node.js

我刚开始使用javascript工作,但很快就陷入了困境 - 在我看来 - 返回一个对象字面的非常简单的任务。

我目前的代码看起来像这样

function wrapInObject(x)
{
    return
    {
        y: x
    };
}
console.log(wrapInObject('someValue'));  

但不是将对象文字写入控制台而是打印undefined - 我尝试使用数字或其他对象文字来调用该函数,但没有任何帮助。

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

这是由于一个称为automatic semicolon insertion的过程,并且经常是具有C#背景或其他语言的新开发人员混淆的根源,其中将左括号放在新行上是常见做法。

基本上发生的事情是在return语句之后放置一个隐式分号,这样它就会返回undefined并且你的对象文字永远不会“到达”。

要修复它,只需将左大括号移动到return的末尾,就像这样

function wrapInObject(x)
{
    return { 
        y: x 
    };
}

答案 1 :(得分:0)

由于自动分号插入

function wrapInObject(x)
{
    return
    {
        y: x
    };
}
console.log(wrapInObject('someValue'));

转换为

function wrapInObject(x)
{
    return ; // semicolon is added
    {
        y: x
    };
}
console.log(wrapInObject('someValue'));  

因此你得到了未定义。

答案 2 :(得分:0)

这是因为分号自动插入在return语句使js引擎解析该行之后添加换行符,就好像有分号一样。将左括号移动到与return语句相同的行。

Another StackOverflow entry about semicolon auto-insertion