return
return 语句结束函数执行并指定要返回给函数调用者的值。
¥The return statement ends function execution and specifies a value to be returned to the function caller.
Try it
语法
描述
¥Description
return 语句只能在函数体内使用。当函数体中使用 return 语句时,函数的执行将停止。return 语句放在不同的函数中具有不同的效果:
¥The return statement can only be used within function bodies. When a return statement is used in a function body, the execution of the function is stopped. The return statement has different effects when placed in different functions:
- 在普通函数中,对该函数的调用计算结果为返回值。
- 在异步函数中,生成的 Promise 通过返回值来解析。
- 在生成器函数中,生成的生成器对象的
next()方法返回{ done: true, value: returnedValue }。 - 在异步生成器函数中,生成的异步生成器对象的
next()方法返回用{ done: true, value: returnedValue }履行的承诺。
如果在 try 块内执行 return 语句,则在实际返回值之前,首先执行其 finally 块(如果存在)。
¥If a return statement is executed within a try block, its finally block, if present, is first executed, before the value is actually returned.
自动插入分号
¥Automatic semicolon insertion
该语法禁止 return 关键字和要返回的表达式之间存在行终止符。
¥The syntax forbids line terminators between the return keyword and the expression to be returned.
return
a + b;
上面的代码经过 自动分号插入 (ASI) 转化为:
¥The code above is transformed by automatic semicolon insertion (ASI) into:
return;
a + b;
这使得函数返回 undefined 并且 a + b 表达式永远不会被计算。这可能会生成 控制台中出现警告。
¥This makes the function return undefined and the a + b expression is never evaluated. This may generate a warning in the console.
为了避免这个问题(防止 ASI),你可以使用括号:
¥To avoid this problem (to prevent ASI), you could use parentheses:
return (
a + b
);
示例
中断函数
¥Interrupt a function
函数立即停止在调用 return 的位置。
¥A function immediately stops at the point where return is called.
function counter() {
// Infinite loop
for (let count = 1; ; count++) {
console.log(`${count}A`); // Until 5
if (count === 5) {
return;
}
console.log(`${count}B`); // Until 4
}
console.log(`${count}C`); // Never appears
}
counter();
// Logs:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A
返回一个函数
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-return-statement |
浏览器兼容性
BCD tables only load in the browser