为什么返回的值应与JavaScript中的return语句位于同一行? [英] Why does the value returned should be on the same line as the return statement in JavaScript?

查看:164
本文介绍了为什么返回的值应与JavaScript中的return语句位于同一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容无法正常工作:

The following doesn't work as I would expect it to:

function test()
{
  // Returns undefined, even though I thought it would return 1
  return
  1;
}

显然,该值应该在同一行:返回1; 。为什么我可以写这样的东西

Apparently, the value should be on the same line: return 1;. Why can I write things like

// Assigns 1 to foo just fine
foo
=
1;

...但是返回声明没有工作方式是否相同?

...but the return statement doesn't work the same way?

推荐答案

如果返回表达式未打开,Javascript会在return语句后自动插入分号同一条线。

Javascript automatically inserts a semicolon after the "return" statement if the return expression is not on the same line.


JavaScript有一种机制,试图通过自动插入分号来纠正错误的程序。不要依赖于此。它可以掩盖更严重的错误。它有时会在不受欢迎的地方插入分号。考虑分号插入对return语句的影响。如果return语句返回一个值,那么该值表达式必须与返回的同一行开始:

JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors. It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of semicolon insertion on the return statement. If a return statement returns a value, that value expression must begin on the same line as the return:



return
{
   status: true
};




这似乎返回一个包含状态成员的对象。
不幸的是,分号插入将其转换为
返回undefined的语句。没有任何警告说分号插入导致
误解了程序。如果
{位于上一行末尾而不是
开头的下一行,则可以避免这个问题:

This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it into a statement that returns undefined. There is no warning that semicolon insertion caused the misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line and not at the beginning of the next line:



return {
   status: true
};

引自这篇文章,引用了道格拉斯克罗克福德的 JavaScript:好的部分。版权所有2008 Yahoo! Inc.,978-0-596-51774-8

Quoted from this post, citing JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc., 978-0-596-51774-8.

这篇关于为什么返回的值应与JavaScript中的return语句位于同一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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