简体   繁体   English

JavaScript中的return语句错误

[英]Error with return statement in javascript

I have this javascript code which is not working. 我有此JavaScript代码无法正常工作。

function myfun()
   {
       return
       {
       alert("para"); 
       } 
   };

   myfun();

I have read about the javascript's automatic semicolon insertion. 我已经阅读了有关javascript的自动分号插入的信息。 I corrected the above code as 我将上面的代码更正为

return{
       alert("para"); 
       } 

But still got the error : unexpected token ( . I wonder why? 但是仍然出现错误: unexpected token ( 。我想知道为什么吗?

NOTE: I don't need the solution but I need the explanation why the above code in not working. 注意:我不需要解决方案,但是我需要解释为什么上面的代码无法正常工作。

EDIT 编辑

According to the book, javascript the good parts, the return statement if returns value must be in same line as return expression. 根据本书,javascript是优秀的部分,return语句如果返回值必须与return表达式在同一行。

ie

 return {
status: true
};

AND

 return
{
status: true
};

Is wrong.Then How come 是错的。那怎么来

function myfun(para)
   {
     var status; 

       return
       {
          status : alert(para)
       };
   };


  myfun("ok");

produce no error.It won't work but shows no error as well.It works when the { is in the same line as return. 不会产生错误。它不会起作用,但也不会显示任何错误。当{与return位于同一行时,它将起作用。

ie

 function myfun(para)
   {
     var status; 

       return{
          status : alert(para)
       };
   };

   myfun("ok");

In

return {
   alert("para"); 
} 

the {...} are interpreted as object literal . {...}被解释为对象文字 An object literal has the form 对象文字具有以下形式

{
    key: value,
    //...
}

Object literals cannot contain arbitrary statements. 对象文字不能包含任意语句。

Looks like you've difficulties with ASI and the difference between run-time and parsing-time. 看起来您在使用ASI以及运行时与解析时之间的差异时遇到了困难。

Where as 在哪里

return {
    status: true
};

is a correct way to return an object, ASI will take an action in the following code: 是返回对象的正确方法,ASI将通过以下代码执行操作:

return
{ //  ^-- ASI will insert a semicolon here
    status: true
};

The semicolon is automatically inserted, and at run-time all lines after return are ignored. 分号将自动插入,并且在运行时将忽略return后的所有行。 However, at parsing time , everything counts, and if there's a syntax error, like in your first example, an error will be thrown. 但是, 在解析时 ,一切都很重要,并且如果有语法错误(如您的第一个示例),将引发错误。

The reason why you are getting that error is because JS is expecting a value to the key "para". 之所以收到该错误,是因为JS期望键“ para”的值。

There is no compulsion to return in a JavaScript function. 没有强制返回JavaScript函数的功能。 If your intention is to test if the control goes to the function, you can simply change it to 如果您打算测试控件是否进入该功能,则只需将其更改为

function myfun() { alert("para"); }

if you want to return an object with string "para" you should change it to 如果要返回带有字符串“ para”的对象,则应将其更改为

function myfun() { return { "text": "para" }; }

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

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