当返回值在新行上时,为什么Javascript return语句不起作用? [英] Why doesn't a Javascript return statement work when the return value is on a new line?

查看:122
本文介绍了当返回值在新行上时,为什么Javascript return语句不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Javascript代码。

Consider the following Javascript code.

<script language="javascript" type="text/javascript">
        function correct()
        {
            return 15;
        }

        function wrong()
        {
            return
                  15;
        }

        alert("correct() called : "+correct());
        alert("wrong() called : "+wrong());

</script>






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 rarely what you actually want.

并且返回语句后跟一个新的line告诉JS intepreter在 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);
}

这里我们以一个开放的开始一个表达式( 。当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.

这篇关于当返回值在新行上时,为什么Javascript return语句不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆