要求
return
语句总是或从不指定值(一致返回)
与强制函数返回指定类型的值的静态类型语言不同,JavaScript 允许函数中的不同代码路径返回不同类型的值。
JavaScript 的一个令人困惑的方面是,
undefined
如果满足以下任一条件,函数将返回:
-
return
在退出之前不执行语句
-
它执行时
return
没有明确指定一个值
-
它执行
return undefined
-
它执行
return void
后跟一个表达式(例如,一个函数调用)
-
它执行
return
之后是任何其他表达式,评估为undefined
如果某个函数中的任何代码路径显式返回一个值,但某些代码路径不会显式返回值,则可能是输入错误,特别是在大型函数中。在以下示例中:
-
通过该函数的代码路径返回一个 Boolean 值
true
-
另一个代码路径不显式返回值,因此隐式返回
undefined
function doSomething(condition) {
if (condition) {
return true;
} else {
return;
}
规则细节
规则要求
return
语句总是或永远不指定值。此规则忽略名称以大写字母开头的函数定义,因为构造函数(当用
new
运算符调用时)隐式返回实例化对象,如果它们不显式返回另一个对象。
规则的 错误 代码示例:
/*eslint consistent-return: "error"*/
function doSomething(condition) {
if (condition) {
return true;
} else {
return;
function doSomething(condition) {
if (condition) {
return true;
}
规则的 正确 代码示例:
/*eslint consistent-return: "error"*/
function doSomething(condition) {
if (condition) {
return true;
} else {
return false;
function Foo() {
if (!(this instanceof Foo)) {
return new Foo();
this.a = 0;
}
选项
规则有一个对象选项:
-
"treatUndefinedAsUnspecified": false
(默认)总是指定值或仅隐式返回undefined
。
-
"treatUndefinedAsUnspecified": true
总是指定值或undefined
显式或隐式返回。
treatUndefinedAsUnspecified
{ "treatUndefinedAsUnspecified": false }
规则的默认代码
错误
代码示例:
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": false }]*/
function foo(callback) {
if (callback) {
return void callback();
// no return statement
function bar(condition) {
if (condition) {
return undefined;
// no return statement
}
{ "treatUndefinedAsUnspecified": true }
规则的
错误
代码示例包含以下选项:
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]*/
function foo(callback) {
if (callback) {
return void callback();
return true;
function bar(condition) {
if (condition) {
return undefined;
return true;
}
{ "treatUndefinedAsUnspecified": true }
规则的
正确
代码示例包含以下选项:
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]*/
function foo(callback) {
if (callback) {
return void callback();
// no return statement