Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年9月.
function* 宣告式(function 關鍵字後面跟著一個星號)定義了一個生成器函式(generator function),他會回傳一個生成器(Generator)物件。
你可以透過 GeneratorFunction 建構式來定義生成器函式。
函式名稱。
param要被傳入函式的引數名稱,一個函式最多可以擁有 255 個引數。
statementsstatements 構成了函式內容的陳述式。
生成器是可以離開後再次進入的函式。在兩次進入之間,生成器的執行狀態(變數綁定狀態)會被儲存。
呼叫生成器函式並不會讓裡面的程式碼立即執行,而是會回傳一個針對該函式的迭代器(iterator)物件。當呼叫迭代器的 next() 方法時,生成器函式將會執行到遭遇的第一個 yield 運算式,該運算式給定的值將從迭代器中回傳,如果是 yield* 則會交給另一個生成器函式處理。next() 方法回傳一個物件,該物件有 value 屬性,包含了產生的數值,還有 done 屬性,為布林值,指出該生成器是否產出最後的數值。呼叫 next() 方法如果帶有一個參數,將會讓先前暫停的生成器函式恢復執行,以該參數值取代先前暫停的 yield 陳述式。
生成器中的 return 陳述式被執行時,會讓生成器 done 狀態為真。若有數值被返回的動作帶回,將是放在 value 傳回的。已返回的生成器不會再產生任何數值。
| ECMAScript® 2027 Language Specification # sec-generator-function-definitions |
Enable JavaScript to view this browser compatibility table.
Older Firefox versions implement an older version of the generators proposal. In the older version, generators were defined using a regular function keyword (without an asterisk) among other differences. See Legacy generator function for further information.
Starting with Gecko 29, the completed generator function no longer throws a TypeError "generator has already finished". Instead, it returns an IteratorResult object like { value: undefined, done: true } (Firefox bug 958951).
This page was last modified on 2025年7月16日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.