当返回值在新行时,为什么 Javascript 返回语句不起作用?

2022-01-19 00:00:00 return javascript

考虑以下 JavaScript:

Consider the following JavaScript:

function correct()
{
    return 15;
}

function wrong()
{
    return
          15;
}

console.log("correct() called : "+correct());
console.log("wrong() called : "+wrong());

上述代码片段中的 correct() 方法返回正确的值,在这种情况下为 15.wrong() 方法却返回 undefined.大多数其他语言并非如此.

The correct() method in the above code snippet returns the correct value which is 15 in this case. The wrong() method, however returns undefined. Such is not the case with the most other languages.

以下函数是正确的,并返回正确的值.

The following function is however correct and returns the correct value.

function wrong()
{
    return(
          15);
}

如果语法错误,它应该会发出一些编译器错误,但它不会.为什么会这样?

If the syntax is wrong, it should issue some compiler error but it doesn't. Why does this happen?

推荐答案

从技术上讲,javascript 中的分号是可选的.但实际上它只是在某些换行符处为您插入它们,如果它认为它们丢失了.但它为您做出的决定并不总是您真正想要的.

Technically, semi colons in javascript are optional. But in reality it just inserts them for you at certain newline characters if it thinks they are missing. But the descisions it makes for you are not always what you actually want.

return 语句后跟一个新行告诉 JS 解释器应该在 return 之后插入一个分号.因此,您的实际代码是这样的:

And a return statement followed by a new line tells the JS intepreter that a semi colon should be inserted after that return. Therefore your actual code is this:

function wrong()
{
    return;
          15;
}

这显然是错误的.那么为什么会这样呢?

Which is obviously wrong. So why does this work?

function wrong()
{
     return(
           15);
}

好吧,这里我们用一个 open( 开始一个表达式.当 JS 找到新行时,它知道我们在一个表达式的中间,并且在这种情况下足够聪明,不会插入任何分号.

Well here we start an expression with an open(. JS knows we are in the middle of an expression when it finds the new line and is smart enough to not insert any semi colons in this case.

相关文章