JavaScript中不可靠的返回语句 [英] A wonky return statement in JavaScript

查看:93
本文介绍了JavaScript中不可靠的返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 函数returnValue(){
回报(
价值);
}

只是将返回值分割成一行。






如果括号对如下所示,那么它返回 undefined

 函数returnValue(){
返回
value;
}

我使用的IDE发出警告,如下所示。


代码没有副作用

值不是 return 语句本身的一部分。



为什么它们的行为不同?

解决方案

因为在Javascript中,语句可以用换行符而不是来终止分号。分号基本上是自动插入的,只在结果可以是完整的语句



return; code>本身是有效的,但是你的函数什么也没有返回,你的value; 没有任何副作用。



另一方面,您的第一个示例无法以这种方式进行解析,因为该行在圆括号的中间结束。



这些规则是在ECMA-262标准文件的§7.9.1中描述。

The following function works and does its intended job - returns the desired value as specified.

function returnValue() {
    return( 
          "value");
}

Just the return value is split into a new line.


If the pair of parentheses is dropped as follows then, it returns undefined.

function returnValue() {
    return 
         "value";
}

The IDE I'm using issues a warning as follows.

Code has no side effects

It seems like "value" is not part of the return statement itself.

Why do they both behave differently?

解决方案

Because in Javascript, a statement can be terminated by a newline instead of a semicolon. The semicolon is essentially inserted automatically, but only where the result can be a full statement.

return; is valid on its own, but then your function returns nothing and your "value"; has no side-effects.

On the other hand, your first example simply cannot be parsed this way because the line ends in the middle of a parenthesis.

These rules are described in §7.9.1 in the ECMA-262 standard document.

这篇关于JavaScript中不可靠的返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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