return
return 語句結束函式的執行,並指定一個值返回給函式呼叫者。
試一試
function getRectArea(width, height) {
if (width > 0 && height > 0) {
return width * height;
}
return 0;
}
console.log(getRectArea(3, 4));
// Expected output: 12
console.log(getRectArea(-3, 4));
// Expected output: 0
語法
js
return;
return expression;
expression可選-
要返回的值的表示式。如果省略,則返回
undefined。
描述
return 語句只能在函式體內部使用。當 return 語句在函式體中使用時,函式的執行將被停止。return 語句在不同的函式中具有不同的效果。
- 在普通函式中,該函式的呼叫將計算為返回值。
- 在非同步函式中,生成的 Promise 將使用返回值進行解析。
- 在生成器函式中,生成的生成器物件的
next()方法返回{ done: true, value: returnedValue }。 - 在非同步生成器函式中,生成的非同步生成器物件的
next()方法返回一個 Promise,該 Promise 使用{ done: true, value: returnedValue }完成。
如果在 try 塊中執行 return 語句,則在實際返回該值之前,如果存在 finally 塊,它將首先執行。
自動分號插入
語法禁止在 return 關鍵字和要返回的表示式之間使用行終止符。
js
return
a + b;
上面的程式碼被自動分號插入 (ASI) 轉換為
js
return;
a + b;
這會使函式返回 undefined,並且 a + b 表示式永遠不會被評估。這可能會在控制檯中生成警告。
為了避免這個問題(防止 ASI),你可以使用括號
js
return (
a + b
);
示例
中斷函式
函式在呼叫 return 的位置立即停止。
js
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
返回函式
另請參閱有關閉包的文章。
js
function magic() {
return function calc(x) {
return x * 42;
};
}
const answer = magic();
answer(1337); // 56154
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-return-statement |
瀏覽器相容性
載入中…