使用 return
指定函数应生成的最终结果值。当解释器到达 return
语句时,
包含该语句立即结束,并且指定的值将返回到
调用该函数的上下文:
const myFunction = function() {
return 2 + 2;
}
myFunction();
> 4
返回值的函数可以有效地视为其包含的数据,类似于变量:
const myFunction = function() {
return 2 + 2;
}
myFunction() + myFunction();
> 8
不带表达式的 return
语句会结束函数并返回 undefined
:
const myFunction = function() {
return;
}
myFunction();
> undefined
由于 return
关键字会指示函数结束,因此任何
遵循所遇到的 return
不会执行:
const myFunction = function() {
return true;
console.log( "This is a string." );
}
myFunction();
> true
此外,在遇到 return
语句后面的代码可能会在某些浏览器的开发者控制台中导致警告(而非错误):
const myFunction = function() {
return true;
console.log( "This is a string." );
}
> unreachable code after return statement
myFunction();
> true
再次强调,这仅适用于函数执行期间遇到的 return
语句,而不适用于紧随 return
语句的任何代码:
const myFunction = function( myParameter ) {
if( myParameter === undefined ) {
return "This is the result.";
}
return "This is the alternate result.";
}
myFunction();
> "This is the result."
myFunction( true );
> "This is the alternate result."
与在函数末尾使用单个 return
语句相比,使用早期 return
对函数进行“短路”可以让代码更简洁。例如,
以下函数可确定传递的值是否为包含五个值的字符串
一个或多个字符。如果传递的值不是字符串字面量,则不需要统计字符的代码,并且函数可以立即返回 false
结果:
function myFunction( myString ) {
if( typeof myString !== "string" ) {
return false;
}
if( myString.length >= 5 ) {
return true;
} else {
return false;
}
}
myFunction( 100 );
> false
myFunction( "St" );
> false
myFunction( "String." );
> true
箭头函数表达式的独特之处在于,当箭头函数正文包含单个表达式且没有块语法时,系统会隐式使用 return
关键字:
const myFunction = () => 2 + 2;
myFunction();
> 4
如果您使用块语法定义箭头函数主体,则必须使用显式 return
,即使函数主体只包含一个表达式也是如此:
const myFunction = () => { 2 + 2 };
myFunction();
> undefined
const myFunction = () => { return 2 + 2 };
myFunction();
> 4
检查您的理解情况
return
有什么用途?
将代码返回到函数开头。
指定函数的最终结果。